file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/42/0xB0Cf2f463b473C96b047f83cd1984A8adFdEc774/sources/DDSDAIPools2.sol
平仓操作move hold Fee to lps user判断盈余与保证金的情况
function close(uint256 id,uint256 profit,uint256 holdFee) public onlyKeeeper returns(uint256 userProfit){ uint256 lpId = matchIds[id]-1; address makerAddr = lockedLiquidity[lpId].makerAddr; lockedLiquidity[lpId].locked = false; uint256 marginAmount = lockedLiquidity[lpId].marginAmount; uint256 marginFee = lockedLiquidity[lpId].marginFee; LP2Account storage lpqAccount = lpAccount[makerAddr]; lpqAccount.amount = lpqAccount.amount.add(holdFee); lpqAccount.availableAmount = lpqAccount.availableAmount.add(holdFee); if (profit > 0){ if (marginAmount >= profit){ userProfit = profit; lpqAccount.availableAmount = lpqAccount.availableAmount.add(marginFee).add(marginAmount.sub(profit)); lpqAccount.amount = lpqAccount.amount.sub(profit); userProfit = profit; uint256 mvRiskFund = marginAmount.add(marginFee).sub(profit); lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)); _safeTransfer(tokenAddress,riskFundAddr,mvRiskFund); uint256 fixAmount = profit.sub(marginAmount.add(marginFee)); if(lpqAccount.availableAmount >= fixAmount){ userProfit = profit; lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)).sub(fixAmount); lpqAccount.availableAmount = lpqAccount.availableAmount.sub(fixAmount); uint256 newFixAmount = fixAmount.sub(lpqAccount.availableAmount); uint256 riskFund = getRiskFundAmount(); if(riskFund >= newFixAmount){ userProfit = profit; _safeTransferFrom(tokenAddress, riskFundAddr,address(this), newFixAmount); userProfit = marginAmount.add(marginFee).add(lpqAccount.availableAmount).add(riskFund); _safeTransferFrom(tokenAddress, riskFundAddr,address(this), riskFund); } lpqAccount.availableAmount = 0; } } } if (profit > 0){ if (marginAmount >= profit){ userProfit = profit; lpqAccount.availableAmount = lpqAccount.availableAmount.add(marginFee).add(marginAmount.sub(profit)); lpqAccount.amount = lpqAccount.amount.sub(profit); userProfit = profit; uint256 mvRiskFund = marginAmount.add(marginFee).sub(profit); lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)); _safeTransfer(tokenAddress,riskFundAddr,mvRiskFund); uint256 fixAmount = profit.sub(marginAmount.add(marginFee)); if(lpqAccount.availableAmount >= fixAmount){ userProfit = profit; lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)).sub(fixAmount); lpqAccount.availableAmount = lpqAccount.availableAmount.sub(fixAmount); uint256 newFixAmount = fixAmount.sub(lpqAccount.availableAmount); uint256 riskFund = getRiskFundAmount(); if(riskFund >= newFixAmount){ userProfit = profit; _safeTransferFrom(tokenAddress, riskFundAddr,address(this), newFixAmount); userProfit = marginAmount.add(marginFee).add(lpqAccount.availableAmount).add(riskFund); _safeTransferFrom(tokenAddress, riskFundAddr,address(this), riskFund); } lpqAccount.availableAmount = 0; } } } }else { if (profit > 0){ if (marginAmount >= profit){ userProfit = profit; lpqAccount.availableAmount = lpqAccount.availableAmount.add(marginFee).add(marginAmount.sub(profit)); lpqAccount.amount = lpqAccount.amount.sub(profit); userProfit = profit; uint256 mvRiskFund = marginAmount.add(marginFee).sub(profit); lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)); _safeTransfer(tokenAddress,riskFundAddr,mvRiskFund); uint256 fixAmount = profit.sub(marginAmount.add(marginFee)); if(lpqAccount.availableAmount >= fixAmount){ userProfit = profit; lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)).sub(fixAmount); lpqAccount.availableAmount = lpqAccount.availableAmount.sub(fixAmount); uint256 newFixAmount = fixAmount.sub(lpqAccount.availableAmount); uint256 riskFund = getRiskFundAmount(); if(riskFund >= newFixAmount){ userProfit = profit; _safeTransferFrom(tokenAddress, riskFundAddr,address(this), newFixAmount); userProfit = marginAmount.add(marginFee).add(lpqAccount.availableAmount).add(riskFund); _safeTransferFrom(tokenAddress, riskFundAddr,address(this), riskFund); } lpqAccount.availableAmount = 0; } } } }else{ if (profit > 0){ if (marginAmount >= profit){ userProfit = profit; lpqAccount.availableAmount = lpqAccount.availableAmount.add(marginFee).add(marginAmount.sub(profit)); lpqAccount.amount = lpqAccount.amount.sub(profit); userProfit = profit; uint256 mvRiskFund = marginAmount.add(marginFee).sub(profit); lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)); _safeTransfer(tokenAddress,riskFundAddr,mvRiskFund); uint256 fixAmount = profit.sub(marginAmount.add(marginFee)); if(lpqAccount.availableAmount >= fixAmount){ userProfit = profit; lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee)).sub(fixAmount); lpqAccount.availableAmount = lpqAccount.availableAmount.sub(fixAmount); uint256 newFixAmount = fixAmount.sub(lpqAccount.availableAmount); uint256 riskFund = getRiskFundAmount(); if(riskFund >= newFixAmount){ userProfit = profit; _safeTransferFrom(tokenAddress, riskFundAddr,address(this), newFixAmount); userProfit = marginAmount.add(marginFee).add(lpqAccount.availableAmount).add(riskFund); _safeTransferFrom(tokenAddress, riskFundAddr,address(this), riskFund); } lpqAccount.availableAmount = 0; } } } lpqAccount.amount = lpqAccount.amount.sub(marginAmount.add(marginFee).add(lpqAccount.availableAmount)); }else{ lpqAccount.availableAmount = lpqAccount.availableAmount.add(marginAmount.add(marginFee)); }
9,599,996
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Invalid owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract EyeToken is ERC20, Ownable { using SafeMath for uint256; struct Frozen { bool frozen; uint until; } string public name = "EYE Token"; string public symbol = "EYE"; uint8 public decimals = 18; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; mapping(address => Frozen) public frozenAccounts; uint256 internal totalSupplyTokens; bool internal isICO; address public wallet; function EyeToken() public Ownable() { wallet = msg.sender; isICO = true; totalSupplyTokens = 10000000000 * 10 ** uint256(decimals); balances[wallet] = totalSupplyTokens; } /** * @dev Finalize ICO */ function finalizeICO() public onlyOwner { isICO = false; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupplyTokens; } /** * @dev Freeze account, make transfers from this account unavailable * @param _account Given account */ function freeze(address _account) public onlyOwner { freeze(_account, 0); } /** * @dev Temporary freeze account, make transfers from this account unavailable for a time * @param _account Given account * @param _until Time until */ function freeze(address _account, uint _until) public onlyOwner { if (_until == 0 || (_until != 0 && _until > now)) { frozenAccounts[_account] = Frozen(true, _until); } } /** * @dev Unfreeze account, make transfers from this account available * @param _account Given account */ function unfreeze(address _account) public onlyOwner { if (frozenAccounts[_account].frozen) { delete frozenAccounts[_account]; } } /** * @dev allow transfer tokens or not * @param _from The address to transfer from. */ modifier allowTransfer(address _from) { require(!isICO, "ICO phase"); if (frozenAccounts[_from].frozen) { require(frozenAccounts[_from].until != 0 && frozenAccounts[_from].until < now, "Frozen account"); delete frozenAccounts[_from]; } _; } /** * @dev transfer tokens for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { bool result = _transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return result; } /** * @dev transfer tokens for a specified address in ICO mode * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferICO(address _to, uint256 _value) public onlyOwner returns (bool) { require(isICO, "Not ICO phase"); require(_to != address(0), "Zero address 'To'"); require(_value <= balances[wallet], "Not enought balance"); balances[wallet] = balances[wallet].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(wallet, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public allowTransfer(_from) returns (bool) { require(_value <= allowed[_from][msg.sender], "Not enought allowance"); bool result = _transfer(_from, _to, _value); if (result) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); } return result; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev transfer token for a specified address * @param _from The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint256 _value) internal allowTransfer(_from) returns (bool) { require(_to != address(0), "Zero address 'To'"); require(_from != address(0), "Zero address 'From'"); require(_value <= balances[_from], "Not enought balance"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); return true; } } /** * @title Crowd-sale * * @dev Crowd-sale contract for tokens */ contract CrowdSale is Ownable { using SafeMath for uint256; event Payment( address wallet, uint date, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent ); uint constant internal MIN_TOKEN_AMOUNT = 5000; uint constant internal SECONDS_IN_DAY = 86400; // 24 * 60 * 60 uint constant internal SECONDS_IN_YEAR = 31557600; // ( 365 * 24 + 6 ) * 60 * 60 int8 constant internal PHASE_NOT_STARTED = -5; int8 constant internal PHASE_BEFORE_PRESALE = -4; int8 constant internal PHASE_BETWEEN_PRESALE_ICO = -3; int8 constant internal PHASE_ICO_FINISHED = -2; int8 constant internal PHASE_FINISHED = -1; int8 constant internal PHASE_PRESALE = 0; int8 constant internal PHASE_ICO_1 = 1; int8 constant internal PHASE_ICO_2 = 2; int8 constant internal PHASE_ICO_3 = 3; int8 constant internal PHASE_ICO_4 = 4; int8 constant internal PHASE_ICO_5 = 5; address internal manager; EyeToken internal token; address internal base_wallet; uint256 internal dec_mul; address internal vest_1; address internal vest_2; address internal vest_3; address internal vest_4; int8 internal phase_i; // see PHASE_XXX uint internal presale_start = 1533020400; // 2018-07-31 07:00 UTC uint internal presale_end = 1534316400; // 2018-08-15 07:00 UTC uint internal ico_start = 1537254000; // 2018-09-18 07:00 UTC uint internal ico_phase_1_days = 7; uint internal ico_phase_2_days = 7; uint internal ico_phase_3_days = 7; uint internal ico_phase_4_days = 7; uint internal ico_phase_5_days = 7; uint internal ico_phase_1_end; uint internal ico_phase_2_end; uint internal ico_phase_3_end; uint internal ico_phase_4_end; uint internal ico_phase_5_end; uint8[6] public bonus_percents = [50, 40, 30, 20, 10, 0]; uint internal finish_date; uint public exchange_rate; // tokens in one ethereum * 1000 uint256 public lastPayerOverflow = 0; /** * @dev Crowd-sale constructor */ function CrowdSale() Ownable() public { phase_i = PHASE_NOT_STARTED; manager = address(0); } /** * @dev Allow only for owner or manager */ modifier onlyOwnerOrManager(){ require(msg.sender == owner || (msg.sender == manager && manager != address(0)), "Invalid owner or manager"); _; } /** * @dev Returns current manager */ function getManager() public view onlyOwnerOrManager returns (address) { return manager; } /** * @dev Sets new manager * @param _manager New manager */ function setManager(address _manager) public onlyOwner { manager = _manager; } /** * @dev Set exchange rate * @param _rate New exchange rate * * executed by CRM */ function setRate(uint _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); exchange_rate = _rate; } function _addPayment(address wallet, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent) internal { emit Payment(wallet, now, amountEth, amountCoin, bonusPercent); } /** * @dev Start crowd-sale * @param _token Coin's contract * @param _rate current exchange rate */ function start(address _token, uint256 _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); require(phase_i == PHASE_NOT_STARTED, "Bad phase"); token = EyeToken(_token); base_wallet = token.wallet(); dec_mul = 10 ** uint256(token.decimals()); // Organizasional expenses address org_exp = 0xeb967ECF00e86F58F6EB8019d003c48186679A96; // Early birds address ear_brd = 0x469A97b357C2056B927fF4CA097513BD927db99E; // Community development address com_dev = 0x877D6a4865478f50219a20870Bdd16E6f7aa954F; // Special coins address special = 0x5D2C58e6aCC5BcC1aaA9b54B007e0c9c3E091adE; // Team lock vest_1 = 0x47997109aE9bEd21efbBBA362957F1b20F435BF3; vest_2 = 0xd031B38d0520aa10450046Dc0328447C3FF59147; vest_3 = 0x32FcE00BfE1fEC48A45DC543224748f280a5c69E; vest_4 = 0x07B489712235197736E207836f3B71ffaC6b1220; token.transferICO(org_exp, 600000000 * dec_mul); token.transferICO(ear_brd, 1000000000 * dec_mul); token.transferICO(com_dev, 1000000000 * dec_mul); token.transferICO(special, 800000000 * dec_mul); token.transferICO(vest_1, 500000000 * dec_mul); token.transferICO(vest_2, 500000000 * dec_mul); token.transferICO(vest_3, 500000000 * dec_mul); token.transferICO(vest_4, 500000000 * dec_mul); exchange_rate = _rate; phase_i = PHASE_BEFORE_PRESALE; _updatePhaseTimes(); } /** * @dev Finalize ICO */ function _finalizeICO() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); phase_i = PHASE_ICO_FINISHED; uint curr_date = now; finish_date = (curr_date < ico_phase_5_end ? ico_phase_5_end : curr_date).add(SECONDS_IN_DAY * 10); } /** * @dev Finalize crowd-sale */ function _finalize() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint date = now.add(SECONDS_IN_YEAR); token.freeze(vest_1, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_2, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_3, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_4, date); token.finalizeICO(); token.transferOwnership(base_wallet); phase_i = PHASE_FINISHED; } /** * @dev Finalize crowd-sale */ function finalize() public onlyOwner { _finalize(); } function _calcPhase() internal view returns (int8) { if (phase_i == PHASE_FINISHED || phase_i == PHASE_NOT_STARTED) return phase_i; uint curr_date = now; if (curr_date >= ico_phase_5_end || token.balanceOf(base_wallet) == 0) return PHASE_ICO_FINISHED; if (curr_date < presale_start) return PHASE_BEFORE_PRESALE; if (curr_date <= presale_end) return PHASE_PRESALE; if (curr_date < ico_start) return PHASE_BETWEEN_PRESALE_ICO; if (curr_date < ico_phase_1_end) return PHASE_ICO_1; if (curr_date < ico_phase_2_end) return PHASE_ICO_2; if (curr_date < ico_phase_3_end) return PHASE_ICO_3; if (curr_date < ico_phase_4_end) return PHASE_ICO_4; return PHASE_ICO_5; } function phase() public view returns (int8) { return _calcPhase(); } /** * @dev Recalculate phase */ function _updatePhase(bool check_can_sale) internal { uint curr_date = now; if (phase_i == PHASE_ICO_FINISHED) { if (curr_date >= finish_date) _finalize(); } else if (phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED) { int8 new_phase = _calcPhase(); if (new_phase == PHASE_ICO_FINISHED && phase_i != PHASE_ICO_FINISHED) _finalizeICO(); else phase_i = new_phase; } if (check_can_sale) require(phase_i >= 0, "Bad phase"); } /** * @dev Update phase end times */ function _updatePhaseTimes() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); if (phase_i < PHASE_ICO_1) ico_phase_1_end = ico_start.add(SECONDS_IN_DAY.mul(ico_phase_1_days)); if (phase_i < PHASE_ICO_2) ico_phase_2_end = ico_phase_1_end.add(SECONDS_IN_DAY.mul(ico_phase_2_days)); if (phase_i < PHASE_ICO_3) ico_phase_3_end = ico_phase_2_end.add(SECONDS_IN_DAY.mul(ico_phase_3_days)); if (phase_i < PHASE_ICO_4) ico_phase_4_end = ico_phase_3_end.add(SECONDS_IN_DAY.mul(ico_phase_4_days)); if (phase_i < PHASE_ICO_5) ico_phase_5_end = ico_phase_4_end.add(SECONDS_IN_DAY.mul(ico_phase_5_days)); if (phase_i != PHASE_ICO_FINISHED) finish_date = ico_phase_5_end.add(SECONDS_IN_DAY.mul(10)); _updatePhase(false); } /** * @dev Send tokens to the specified address * * @param _to Address sent to * @param _amount_coin Amount of tockens * @return excess coins * * executed by CRM */ function transferICO(address _to, uint256 _amount_coin) public onlyOwnerOrManager { _updatePhase(true); uint256 remainedCoin = token.balanceOf(base_wallet); require(remainedCoin >= _amount_coin, "Not enough coins"); token.transferICO(_to, _amount_coin); if (remainedCoin == _amount_coin) _finalizeICO(); } /** * @dev Default contract function. Buy tokens by sending ethereums */ function() public payable { _updatePhase(true); address sender = msg.sender; uint256 amountEth = msg.value; uint256 remainedCoin = token.balanceOf(base_wallet); if (remainedCoin == 0) { sender.transfer(amountEth); _finalizeICO(); } else { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 amountCoin = calcTokensFromEth(amountEth); assert(amountCoin >= MIN_TOKEN_AMOUNT); if (amountCoin > remainedCoin) { lastPayerOverflow = amountCoin.sub(remainedCoin); amountCoin = remainedCoin; } base_wallet.transfer(amountEth); token.transferICO(sender, amountCoin); _addPayment(sender, amountEth, amountCoin, percent); if (amountCoin == remainedCoin) _finalizeICO(); } } function calcTokensFromEth(uint256 ethAmount) internal view returns (uint256) { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 bonusRate = uint256(percent).add(100); uint256 totalCoins = ethAmount.mul(exchange_rate).div(1000); uint256 totalFullCoins = (totalCoins.add(dec_mul.div(2))).div(dec_mul); uint256 tokensWithBonusX100 = bonusRate.mul(totalFullCoins); uint256 fullCoins = (tokensWithBonusX100.add(50)).div(100); return fullCoins.mul(dec_mul); } /** * @dev Freeze the account * @param _accounts Given accounts * * executed by CRM */ function freeze(address[] _accounts) public onlyOwnerOrManager { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.freeze(_accounts[i]); } } /** * @dev Unfreeze the account * @param _accounts Given accounts */ function unfreeze(address[] _accounts) public onlyOwnerOrManager { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.unfreeze(_accounts[i]); } } /** * @dev get ICO times * @return presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end */ function getTimes() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end); } /** * @dev Sets start and end dates for pre-sale phase_i * @param _presale_start Pre-sale sart date * @param _presale_end Pre-sale end date */ function setPresaleDates(uint _presale_start, uint _presale_end) public onlyOwnerOrManager { _updatePhase(false); require(phase_i == PHASE_BEFORE_PRESALE, "Bad phase"); // require(_presale_start >= now); require(_presale_start < _presale_end, "Invalid presale dates"); require(_presale_end < ico_start, "Invalid dates"); presale_start = _presale_start; presale_end = _presale_end; } /** * @dev Sets start date for ICO phases * @param _ico_start ICO start date * @param _ico_1_days Days of ICO phase 1 * @param _ico_2_days Days of ICO phase 2 * @param _ico_3_days Days of ICO phase 3 * @param _ico_4_days Days of ICO phase 4 * @param _ico_5_days Days of ICO phase 5 */ function setICODates(uint _ico_start, uint _ico_1_days, uint _ico_2_days, uint _ico_3_days, uint _ico_4_days, uint _ico_5_days) public onlyOwnerOrManager { _updatePhase(false); require(phase_i != PHASE_FINISHED && phase_i != PHASE_ICO_FINISHED && phase_i < PHASE_ICO_1, "Bad phase"); require(presale_end < _ico_start, "Invalid dates"); ico_start = _ico_start; ico_phase_1_days = _ico_1_days; ico_phase_2_days = _ico_2_days; ico_phase_3_days = _ico_3_days; ico_phase_4_days = _ico_4_days; ico_phase_5_days = _ico_5_days; _updatePhaseTimes(); } }
Finalize ICO/
function _finalizeICO() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); phase_i = PHASE_ICO_FINISHED; uint curr_date = now; finish_date = (curr_date < ico_phase_5_end ? ico_phase_5_end : curr_date).add(SECONDS_IN_DAY * 10); }
5,403,623
pragma solidity 0.5.4; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function claimEcoSystemReservePart1() public; function claimEcoSystemReservePart2() public; function recoverToken(address _token) public; function claimTeamReserve() public; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title The Multisig contract contains functions to transfer ETH and LYMPO tokens. * @author Roman Holovay */ contract Multisig { struct WithdrawEtherStruct { address payable toAddr; uint amount; address[] confirmators; bool completed; } struct SendTokensStruct { address toAddr; uint amount; address[] confirmators; bool completed; } IERC20 public token; WithdrawEtherStruct[] public withdrawEther; SendTokensStruct[] public sendTokens; uint public confirmationCount; mapping(address => bool) public owners; modifier onlyOwners { require(owners[msg.sender]); _; } constructor(address _tokenAddress, address[] memory _addresses, uint _confirmationCount) public { require(_addresses.length >= _confirmationCount && _confirmationCount > 1); for (uint i = 0; i < _addresses.length; i++){ owners[_addresses[i]] = true; } token = IERC20(_tokenAddress); confirmationCount = _confirmationCount; } /** * @dev changeTokenAddress changing token address only when it is not set yet. * @param _tokenAddress New token address. */ function changeTokenAddress(address _tokenAddress) public { require (owners[msg.sender]); require (token == IERC20(address(0))); token = IERC20(_tokenAddress); } /** * @dev createNewEtherWithdrawRequest creates a new ETH transfer request * @param _toAddr The addresses that will receive ETH. * @param _amount The number of ETH that can be received. */ function createNewEtherWithdrawRequest(address payable _toAddr, uint _amount) public onlyOwners { address[] memory conf; withdrawEther.push(WithdrawEtherStruct(_toAddr, _amount, conf, false)); withdrawEther[withdrawEther.length-1].confirmators.push(msg.sender); } /** * @dev approveEtherWithdrawRequest approve already created ETH transfer request. * This function can be used only by one of owners. * @param withdrawEtherId means position of withdrawEther array. */ function approveEtherWithdrawRequest(uint withdrawEtherId) public onlyOwners { require(!withdrawEther[withdrawEtherId].completed); for (uint i = 0; i < withdrawEther[withdrawEtherId].confirmators.length; i++) { require (msg.sender != withdrawEther[withdrawEtherId].confirmators[i]); } withdrawEther[withdrawEtherId].confirmators.push(msg.sender); if (withdrawEther[withdrawEtherId].confirmators.length >= confirmationCount) { withdrawEther[withdrawEtherId].completed = true; withdrawEther[withdrawEtherId].toAddr.transfer(withdrawEther[withdrawEtherId].amount); } } /** * @dev createTransferTokensRequest creates a new Token transfer request * @param _toAddr The addresses that will receive tokens. * @param _amount The number of tokens that can be received. */ function createTransferTokensRequest(address _toAddr, uint _amount) public onlyOwners { address[] memory conf; sendTokens.push(SendTokensStruct(_toAddr, _amount, conf, false)); sendTokens[sendTokens.length-1].confirmators.push(msg.sender); } /** * @dev approveEtherWithdrawRequest approve already created ETH transfer request. * This function can be used only by one of owners. * @param sendTokensId means position of sendTokens array. */ function approveTransferTokensRequest(uint sendTokensId) public onlyOwners { require(!sendTokens[sendTokensId].completed); for (uint i = 0; i < sendTokens[sendTokensId].confirmators.length; i++) { require(msg.sender != sendTokens[sendTokensId].confirmators[i]); } sendTokens[sendTokensId].confirmators.push(msg.sender); if (sendTokens[sendTokensId].confirmators.length >= confirmationCount) { sendTokens[sendTokensId].completed = true; token.transfer(sendTokens[sendTokensId].toAddr, sendTokens[sendTokensId].amount); } } function claimTeamReserve() public onlyOwners { token.claimTeamReserve(); } function claimEcoSystemReservePart1() public onlyOwners { token.claimEcoSystemReservePart1(); } function claimEcoSystemReservePart2() public onlyOwners { token.claimEcoSystemReservePart2(); } function recoverToken(address _token) public onlyOwners { token.recoverToken(_token); } }
approveEtherWithdrawRequest approve already created ETH transfer request. This function can be used only by one of owners. withdrawEtherId means position of withdrawEther array./
function approveEtherWithdrawRequest(uint withdrawEtherId) public onlyOwners { require(!withdrawEther[withdrawEtherId].completed); for (uint i = 0; i < withdrawEther[withdrawEtherId].confirmators.length; i++) { require (msg.sender != withdrawEther[withdrawEtherId].confirmators[i]); } withdrawEther[withdrawEtherId].confirmators.push(msg.sender); if (withdrawEther[withdrawEtherId].confirmators.length >= confirmationCount) { withdrawEther[withdrawEtherId].completed = true; withdrawEther[withdrawEtherId].toAddr.transfer(withdrawEther[withdrawEtherId].amount); } }
1,752,869
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol
Upon deployment of a RoboToken, need to init it here. This takes care of the setRoboToken() functionality too. This is an internal system contract call this validates the entered portfolioId is valid, and that the portfolio is set-up correctly make it valid
function initRoboToken(address roboTokenAddress, bytes32 portfolioId) external onlyAdmin { roboTokens[roboTokenAddress].portfolioId = portfolioId; roboTokens[roboTokenAddress].opportunities = IStorage(rayStorage).getOpportunities(portfolioId); require( roboTokens[roboTokenAddress].opportunities.length > 0, "#RAYv2 initRoboToken: Opportunities length must be greater than zero." ); roboTokenStatus[roboTokenAddress] = true; }
8,750,787
pragma solidity ^0.4.23; // * dice2.win - fair games that pay Ether. // * Ethereum smart contract, deployed at 0xD1CEeee3ecFff60d9532C37c9d24f68cA0E96453 // * Uses hybrid commit-reveal + block hash random number generation that is immune // to tampering by players, house and miners. Apart from being fully transparent, // this also allows arbitrarily high bets. // * Refer to https://dice2.win/whitepaper.pdf for detailed description and proofs. contract Dice2Win { /// *** Constants section // Chance to win jackpot - currently 0.1% uint constant JACKPOT_MODULO = 1000; // Each bet is deducted 2% amount - 1% is house edge, 1% goes to jackpot fund. uint constant HOUSE_EDGE_PERCENT = 2; uint constant JACKPOT_FEE_PERCENT = 50; // There is a minimum and maximum bets. Minimum is dictated by the gas usage // of settlement transactions, and maximum is just some safe & sane number. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; // Bets lower than this amount do not participate in jackpot rolls. uint constant MIN_JACKPOT_BET = 0.1 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint constant MAX_MODULO = 100; // For modulos below this threshold rolls are checked against a bit mask, // thus allowing betting on any combination of outcomes. For example, given // modulo 6 for dice, 101000 mask (base-2, big endian) means betting on // 4 and 6; for games with modulos higher than threshold (Etheroll), a simple // limit is used, allowing betting on any outcome in [0, N) range. // // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions dice2.win croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address public owner; address private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address gambler; } // Mapping from commits to all currently active & processed bets. mapping (uint => Bet) bets; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed _beneficiary, uint amount); event Payment(address indexed _beneficiary, uint amount); event JackpotPayment(address indexed _beneficiary, uint amount); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () public payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint newMaxProfit) public onlyOwner { require (newMaxProfit < MAX_AMOUNT); maxProfit = newMaxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the dice2.win croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require (bet.gambler == address(0)); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO); require (amount >= MIN_BET && amount <= MAX_AMOUNT); require (betMask > 0 && betMask < MAX_BET_MASK); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock); bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit)); require (secretSigner == ecrecover(signatureHash, 27, r, s)); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder); uint jackpotFee = getJackpotFee(amount); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // Settlement transaction - can in theory be issued by anyone, but is designed to be // handled by the dice2.win croupier bot. To settle a bet with a specific "commit", // settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". clean_commit is some previously 'processed' bet, that will be moved into // 'clean' state to prevent blockchain bloat and refund some gas. function settleBet(uint reveal, uint clean_commit) external { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; uint placeBlockNumber = bet.placeBlockNumber; address gambler = bet.gambler; // Check that bet is in 'active' state. require (amount != 0); // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber))); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Tally up the win. uint totalWin = diceWin + jackpotWin; if (totalWin == 0) { totalWin = 1 wei; } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, totalWin, diceWin); // Clear storage of some previous bet. if (clean_commit == 0) { return; } clearProcessedBet(clean_commit); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the dice2.win support, however nothing // precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS); // Move bet into 'processed' state, release funds. bet.amount = 0; lockedInBets -= uint128(getDiceWinAmount(amount, bet.modulo, bet.rollUnder)); // Send the refund. sendFunds(bet.gambler, amount, amount); } // A helper routine to bulk clean the storage. function clearStorage(uint[] clean_commits) external { uint length = clean_commits.length; for (uint i = 0; i < length; i++) { clearProcessedBet(clean_commits[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint commit) private { Bet storage bet = bets[commit]; // Do not overwrite active bets with zeros; additionally prevent cleanup of bets // for which commit signatures may have not expired yet (see whitepaper for details). if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS) { return; } // Zero out the remaining storage (amount was zeroed before, delete would consume 5k // more gas). bet.modulo = 0; bet.rollUnder = 0; bet.placeBlockNumber = 0; bet.mask = 0; bet.gambler = address(0); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) pure private returns (uint) { require (0 < rollUnder && rollUnder <= modulo); return amount * modulo / rollUnder * (100 - HOUSE_EDGE_PERCENT) / 100; } // Get the portion of bet amount that is to be accumulated in the jackpot. function getJackpotFee(uint amount) pure private returns (uint) { return amount * HOUSE_EDGE_PERCENT / 100 * JACKPOT_FEE_PERCENT / 100; } // Helper routine to process the payment. function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 1 + 2**41 + 2**(41*2) + 2**(41*3) + 2**(41*4) + 2**(41*5); uint constant POPCNT_MASK = 1 + 2**(6*1) + 2**(6*2) + 2**(6*3) + 2**(6*4) + 2**(6*5) + 2**(6*6) + 2**(6*7) + 2**(6*8) + 2**(6*9) + 2**(6*10) + 2**(6*11) + 2**(6*12) + 2**(6*13) + 2**(6*14) + 2**(6*15) + 2**(6*16) + 2**(6*17) + 2**(6*18) + 2**(6*19) + 2**(6*20) + 2**(6*21) + 2**(6*22) + 2**(6*23) + 2**(6*24) + 2**(6*25) + 2**(6*26) + 2**(6*27) + 2**(6*28) + 2**(6*29) + 2**(6*30) + 2**(6*31) + 2**(6*32) + 2**(6*33) + 2**(6*34) + 2**(6*35) + 2**(6*36) + 2**(6*37) + 2**(6*38) + 2**(6*39) + 2**(6*40); uint constant POPCNT_MODULO = 2**6 - 1; }
Settlement transaction - can in theory be issued by anyone, but is designed to be handled by the dice2.win croupier bot. To settle a bet with a specific "commit", settleBet should supply a "reveal" number that would Keccak256-hash to "commit". clean_commit is some previously 'processed' bet, that will be moved into 'clean' state to prevent blockchain bloat and refund some gas. "commit" for bet settlement can only be obtained by hashing a "reveal". Fetch bet parameters into local variables (to save gas). Check that bet is in 'active' state. Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). Move bet into 'processed' state already. The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 preimage is intractable), and house is unable to alter the "reveal" after placeBet have been mined (as Keccak256 collision finding is also intractable). Do a roll by taking a modulo of entropy. Compute winning amount. Determine dice outcome. For small modulo games, check the outcome against a bit mask. For larger modulos, check inclusion into half-open interval. Roll for a jackpot (if eligible). The second modulo, statistically independent from the "main" dice roll. Effectively you are playing two games at once! Bingo! Log jackpot win. Clear storage of some previous bet.
function settleBet(uint reveal, uint clean_commit) external { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; uint placeBlockNumber = bet.placeBlockNumber; address gambler = bet.gambler; require (amount != 0); require (block.number > placeBlockNumber); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS); bet.amount = 0; bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber))); uint dice = uint(entropy) % modulo; uint diceWinAmount = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } if (dice < rollUnder) { diceWin = diceWinAmount; } } if (amount >= MIN_JACKPOT_BET) { uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } if (totalWin == 0) { totalWin = 1 wei; } if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } if (clean_commit == 0) { return; } clearProcessedBet(clean_commit); }
14,556,606
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IEpochUtils.sol pragma solidity 0.6.6; interface IEpochUtils { function epochPeriodInSeconds() external view returns (uint256); function firstEpochStartTimestamp() external view returns (uint256); function getCurrentEpochNumber() external view returns (uint256); function getEpochNumber(uint256 timestamp) external view returns (uint256); } // File: contracts/interfaces/IKyberDao.sol pragma solidity 0.6.6; interface IKyberDao is IEpochUtils { event Voted( address indexed staker, uint256 indexed epoch, uint256 indexed campaignID, uint256 option ); function getLatestNetworkFeeDataWithCache() external returns (uint256 feeInBps, uint256 expiryTimestamp); function getLatestBRRDataWithCache() external returns ( uint256 burnInBps, uint256 rewardInBps, uint256 rebateInBps, uint256 epoch, uint256 expiryTimestamp ); function handleWithdrawal(address staker, uint256 penaltyAmount) external; function vote(uint256 campaignID, uint256 option) external; function getLatestNetworkFeeData() external view returns (uint256 feeInBps, uint256 expiryTimestamp); function shouldBurnRewardForEpoch(uint256 epoch) external view returns (bool); /** * @dev return staker's reward percentage in precision for a past epoch only * fee handler should call this function when a staker wants to claim reward * return 0 if staker has no votes or stakes */ function getPastEpochRewardPercentageInPrecision( address staker, uint256 epoch ) external view returns (uint256); /** * @dev return staker's reward percentage in precision for the current epoch * reward percentage is not finalized until the current epoch is ended */ function getCurrentEpochRewardPercentageInPrecision(address staker) external view returns (uint256); } // File: contracts/interfaces/IExtendedKyberDao.sol pragma solidity 0.6.6; interface IExtendedKyberDao is IKyberDao { function kncToken() external view returns (address); function staking() external view returns (address); function feeHandler() external view returns (address); } // File: contracts/interfaces/IKyberFeeHandler.sol pragma solidity 0.6.6; interface IKyberFeeHandler { event RewardPaid( address indexed staker, uint256 indexed epoch, IERC20 indexed token, uint256 amount ); event RebatePaid( address indexed rebateWallet, IERC20 indexed token, uint256 amount ); event PlatformFeePaid( address indexed platformWallet, IERC20 indexed token, uint256 amount ); event KncBurned(uint256 kncTWei, IERC20 indexed token, uint256 amount); function handleFees( IERC20 token, address[] calldata eligibleWallets, uint256[] calldata rebatePercentages, address platformWallet, uint256 platformFee, uint256 networkFee ) external payable; function claimReserveRebate(address rebateWallet) external returns (uint256); function claimPlatformFee(address platformWallet) external returns (uint256); function claimStakerReward(address staker, uint256 epoch) external returns (uint256 amount); } // File: contracts/interfaces/IExtendedKyberFeeHandler.sol pragma solidity 0.6.6; interface IExtendedKyberFeeHandler is IKyberFeeHandler { function rewardsPerEpoch(uint256) external view returns (uint256); } // File: contracts/interfaces/IKyberStaking.sol pragma solidity 0.6.6; interface IKyberStaking is IEpochUtils { event Delegated( address indexed staker, address indexed representative, uint256 indexed epoch, bool isDelegated ); event Deposited(uint256 curEpoch, address indexed staker, uint256 amount); event Withdraw( uint256 indexed curEpoch, address indexed staker, uint256 amount ); function initAndReturnStakerDataForCurrentEpoch(address staker) external returns ( uint256 stake, uint256 delegatedStake, address representative ); function deposit(uint256 amount) external; function delegate(address dAddr) external; function withdraw(uint256 amount) external; /** * @notice return combine data (stake, delegatedStake, representative) of a staker * @dev allow to get staker data up to current epoch + 1 */ function getStakerData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); function getLatestStakerData(address staker) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); /** * @notice return raw data of a staker for an epoch * WARN: should be used only for initialized data * if data has not been initialized, it will return all 0 * pool master shouldn't use this function to compute/distribute rewards of pool members */ function getStakerRawData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); } // File: contracts/KyberPoolMaster.sol pragma solidity 0.6.6; pragma experimental ABIEncoderV2; /** * @title Kyber PoolMaster contract * @author Protofire * @dev Contract that allows pool masters to let pool members claim their designated rewards trustlessly and update fees * with sufficient notice times while maintaining full trustlessness. */ contract KyberPoolMaster is Ownable { using SafeMath for uint256; uint256 internal constant MINIMUM_EPOCH_NOTICE = 1; uint256 internal constant MAX_DELEGATION_FEE = 10000; uint256 internal constant PRECISION = (10**18); IERC20 internal constant ETH_TOKEN_ADDRESS = IERC20( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); // Number of epochs after which a change on delegationFee will be applied uint256 public immutable epochNotice; // Mapping of if staker has claimed reward for Epoch in a feeHandler // epoch -> member -> feeHandler -> true | false mapping(uint256 => mapping(address => mapping(address => bool))) public claimedDelegateReward; struct Claim { bool claimedByPool; uint256 totalRewards; uint256 totalStaked; } //epoch -> feeHandler -> Claim mapping(uint256 => mapping(address => Claim)) public epochFeeHandlerClaims; // Fee charged by poolMasters to poolMembers for services // Denominated in 1e4 units // 100 = 1% struct DFeeData { uint256 fromEpoch; uint256 fee; bool applied; } DFeeData[] public delegationFees; IERC20 public immutable kncToken; IExtendedKyberDao public immutable kyberDao; IKyberStaking public immutable kyberStaking; address[] public feeHandlersList; mapping(address => IERC20) public rewardTokenByFeeHandler; uint256 public immutable firstEpoch; mapping(address => bool) public successfulClaimByFeeHandler; struct RewardInfo { IExtendedKyberFeeHandler kyberFeeHandler; IERC20 rewardToken; uint256 totalRewards; uint256 totalFee; uint256 rewardsAfterFee; uint256 poolMembersShare; uint256 poolMasterShare; } struct UnclaimedRewardData { uint256 epoch; address feeHandler; uint256 rewards; IERC20 rewardToken; } /*** Events ***/ event CommitNewFees(uint256 deadline, uint256 feeRate); event NewFees(uint256 fromEpoch, uint256 feeRate); event MemberClaimReward( uint256 indexed epoch, address indexed poolMember, address indexed feeHandler, IERC20 rewardToken, uint256 reward ); event MasterClaimReward( uint256 indexed epoch, address indexed feeHandler, address indexed poolMaster, IERC20 rewardToken, uint256 totalRewards, uint256 feeApplied, uint256 feeAmount, uint256 poolMasterShare ); event AddFeeHandler(address indexed feeHandler, IERC20 indexed rewardToken); event RemoveFeeHandler(address indexed feeHandler); /** * @notice Address deploying this contract should be able to receive ETH, owner can be changed using transferOwnership method * @param _kyberDao KyberDao contract address * @param _epochNotice Number of epochs after which a change on deledatioFee is will be applied * @param _delegationFee Fee charged by poolMasters to poolMembers for services - Denominated in 1e4 units - 100 = 1% * @param _kyberFeeHandlers Array of FeeHandlers * @param _rewardTokens Array of ERC20 tokens used by FeeHandlers to pay reward. Use zero address if FeeHandler pays ETH */ constructor( address _kyberDao, uint256 _epochNotice, uint256 _delegationFee, address[] memory _kyberFeeHandlers, IERC20[] memory _rewardTokens ) public { require(_kyberDao != address(0), "ctor: kyberDao is missing"); require( _epochNotice >= MINIMUM_EPOCH_NOTICE, "ctor: Epoch Notice too low" ); require( _delegationFee <= MAX_DELEGATION_FEE, "ctor: Delegation Fee greater than 100%" ); require( _kyberFeeHandlers.length > 0, "ctor: at least one _kyberFeeHandlers required" ); require( _kyberFeeHandlers.length == _rewardTokens.length, "ctor: _kyberFeeHandlers and _rewardTokens uneven" ); IExtendedKyberDao _kyberDaoContract = IExtendedKyberDao(_kyberDao); kyberDao = _kyberDaoContract; kncToken = IERC20(_kyberDaoContract.kncToken()); kyberStaking = IKyberStaking(_kyberDaoContract.staking()); epochNotice = _epochNotice; uint256 _firstEpoch = _kyberDaoContract.getCurrentEpochNumber(); firstEpoch = _firstEpoch; delegationFees.push(DFeeData(_firstEpoch, _delegationFee, true)); for (uint256 i = 0; i < _kyberFeeHandlers.length; i++) { require( _kyberFeeHandlers[i] != address(0), "ctor: feeHandler is missing" ); require( rewardTokenByFeeHandler[_kyberFeeHandlers[i]] == IERC20(address(0)), "ctor: repeated feeHandler" ); feeHandlersList.push(_kyberFeeHandlers[i]); rewardTokenByFeeHandler[_kyberFeeHandlers[i]] = _rewardTokens[i]; emit AddFeeHandler( _kyberFeeHandlers[i], rewardTokenByFeeHandler[_kyberFeeHandlers[i]] ); } emit CommitNewFees(_firstEpoch, _delegationFee); emit NewFees(_firstEpoch, _delegationFee); } /** * @dev adds a new FeeHandler * @param _feeHandler FeeHandler address * @param _rewardToken Rewards Token address */ function addFeeHandler(address _feeHandler, IERC20 _rewardToken) external onlyOwner { require( _feeHandler != address(0), "addFeeHandler: _feeHandler is missing" ); require( rewardTokenByFeeHandler[_feeHandler] == IERC20(address(0)), "addFeeHandler: already added" ); feeHandlersList.push(_feeHandler); rewardTokenByFeeHandler[_feeHandler] = _rewardToken; emit AddFeeHandler(_feeHandler, rewardTokenByFeeHandler[_feeHandler]); } /** * @dev removes a FeeHandler * @param _feeHandler FeeHandler address */ function removeFeeHandler(address _feeHandler) external onlyOwner { require( rewardTokenByFeeHandler[_feeHandler] != IERC20(address(0)), "removeFeeHandler: not added" ); require( !successfulClaimByFeeHandler[_feeHandler], "removeFeeHandler: can not remove FeeHandler successfully claimed" ); if (feeHandlersList[feeHandlersList.length - 1] != _feeHandler) { for (uint256 i = 0; i < feeHandlersList.length; i++) { if (feeHandlersList[i] == _feeHandler) { feeHandlersList[i] = feeHandlersList[feeHandlersList .length - 1]; break; } } } feeHandlersList.pop(); delete rewardTokenByFeeHandler[_feeHandler]; emit RemoveFeeHandler(_feeHandler); } /** * @dev call to stake more KNC for poolMaster * @param amount amount of KNC to stake */ function masterDeposit(uint256 amount) external onlyOwner { require( amount > 0, "masterDeposit: amount to deposit should be positive" ); require( kncToken.transferFrom(msg.sender, address(this), amount), "masterDeposit: can not get token" ); // approve kncToken.approve(address(kyberStaking), amount); // deposit in KyberStaking kyberStaking.deposit(amount); } /** * @dev call to withdraw KNC from staking * @param amount amount of KNC to withdraw */ function masterWithdraw(uint256 amount) external onlyOwner { require(amount > 0, "masterWithdraw: amount is 0"); // withdraw from KyberStaking kyberStaking.withdraw(amount); // transfer KNC back to pool master require( kncToken.transfer(msg.sender, amount), "masterWithdraw: can not transfer knc to the pool master" ); } /** * @dev vote for an option of a campaign * options are indexed from 1 to number of options * @param campaignID id of campaign to vote for * @param option id of options to vote for */ function vote(uint256 campaignID, uint256 option) external onlyOwner { kyberDao.vote(campaignID, option); } /** * @dev set a new delegation fee to be applied in current epoch + epochNotice * @param _fee new fee */ function commitNewFee(uint256 _fee) external onlyOwner { require( _fee <= MAX_DELEGATION_FEE, "commitNewFee: Delegation Fee greater than 100%" ); uint256 curEpoch = kyberDao.getCurrentEpochNumber(); uint256 fromEpoch = curEpoch.add(epochNotice); DFeeData storage lastFee = delegationFees[delegationFees.length - 1]; if (lastFee.fromEpoch > curEpoch) { lastFee.fromEpoch = fromEpoch; lastFee.fee = _fee; } else { if (!lastFee.applied) { applyFee(lastFee); } delegationFees.push(DFeeData(fromEpoch, _fee, false)); } emit CommitNewFees(fromEpoch.sub(1), _fee); } /** * @dev Applies the pending new fee */ function applyPendingFee() public { DFeeData storage lastFee = delegationFees[delegationFees.length - 1]; uint256 curEpoch = kyberDao.getCurrentEpochNumber(); if (lastFee.fromEpoch <= curEpoch && !lastFee.applied) { applyFee(lastFee); } } /** * @dev Applies a pending fee * @param fee to be applied */ function applyFee(DFeeData storage fee) internal { fee.applied = true; emit NewFees(fee.fromEpoch, fee.fee); } /** * @dev Gets the id of the delegation fee corresponding to the given epoch * @param _epoch for which epoch is querying delegation fee * @param _from delegationFees starting index */ function getEpochDFeeDataId(uint256 _epoch, uint256 _from) internal view returns (uint256) { if (delegationFees[_from].fromEpoch > _epoch) { return _from; } uint256 left = _from; uint256 right = delegationFees.length; while (left < right) { uint256 m = (left + right).div(2); if (delegationFees[m].fromEpoch > _epoch) { right = m; } else { left = m + 1; } } return right - 1; } /** * @dev Gets the the delegation fee data corresponding to the given epoch * @param epoch for which epoch is querying delegation fee */ function getEpochDFeeData(uint256 epoch) public view returns (DFeeData memory epochDFee) { epochDFee = delegationFees[getEpochDFeeDataId(epoch, 0)]; } /** * @dev Gets the the delegation fee data corresponding to the current epoch */ function delegationFee() public view returns (DFeeData memory) { uint256 curEpoch = kyberDao.getCurrentEpochNumber(); return getEpochDFeeData(curEpoch); } /** * @dev Queries the amount of unclaimed rewards for the pool in a given epoch and feeHandler * return 0 if PoolMaster has calledRewardMaster * return 0 if staker's reward percentage in precision for the epoch is 0 * return 0 if total reward for the epoch is 0 * @param _epoch for which epoch is querying unclaimed reward * @param _feeHandler FeeHandler address */ function getUnclaimedRewards( uint256 _epoch, IExtendedKyberFeeHandler _feeHandler ) public view returns (uint256) { if (epochFeeHandlerClaims[_epoch][address(_feeHandler)].claimedByPool) { return 0; } uint256 perInPrecision = kyberDao .getPastEpochRewardPercentageInPrecision(address(this), _epoch); if (perInPrecision == 0) { return 0; } uint256 rewardsPerEpoch = _feeHandler.rewardsPerEpoch(_epoch); if (rewardsPerEpoch == 0) { return 0; } return rewardsPerEpoch.mul(perInPrecision).div(PRECISION); } /** * @dev Returns data related to all epochs and feeHandlers with unclaimed rewards, for the pool. */ function getUnclaimedRewardsData() external view returns (UnclaimedRewardData[] memory) { uint256 currentEpoch = kyberDao.getCurrentEpochNumber(); uint256 maxEpochNumber = currentEpoch.sub(firstEpoch); uint256[] memory epochGroup = new uint256[](maxEpochNumber); uint256 e = 0; for (uint256 epoch = firstEpoch; epoch < currentEpoch; epoch++) { epochGroup[e] = epoch; e++; } return _getUnclaimedRewardsData(epochGroup, feeHandlersList); } /** * @dev Returns data related to all epochs and feeHandlers, from the given groups, with unclaimed rewards, for the pool. */ function getUnclaimedRewardsData( uint256[] calldata _epochGroup, address[] calldata _feeHandlerGroup ) external view returns (UnclaimedRewardData[] memory) { return _getUnclaimedRewardsData(_epochGroup, _feeHandlerGroup); } function _getUnclaimedRewardsData( uint256[] memory _epochGroup, address[] memory _feeHandlerGroup ) internal view returns (UnclaimedRewardData[] memory) { UnclaimedRewardData[] memory epochFeeHanlderRewards = new UnclaimedRewardData[]( _epochGroup.length.mul(_feeHandlerGroup.length) ); uint256 rewardsCounter = 0; for (uint256 e = 0; e < _epochGroup.length; e++) { for (uint256 f = 0; f < _feeHandlerGroup.length; f++) { uint256 unclaimed = getUnclaimedRewards( _epochGroup[e], IExtendedKyberFeeHandler(_feeHandlerGroup[f]) ); if (unclaimed > 0) { epochFeeHanlderRewards[rewardsCounter] = UnclaimedRewardData( _epochGroup[e], _feeHandlerGroup[f], unclaimed, rewardTokenByFeeHandler[_feeHandlerGroup[f]] ); rewardsCounter++; } } } UnclaimedRewardData[] memory result = new UnclaimedRewardData[]( rewardsCounter ); for (uint256 i = 0; i < (rewardsCounter); i++) { result[i] = epochFeeHanlderRewards[i]; } return result; } /** * @dev Claims rewards for a given group of epochs in all feeHandlers, distribute fees and its share to poolMaster * @param _epochGroup An array of epochs for which rewards are being claimed. Asc order and uniqueness is required. */ function claimRewardsMaster(uint256[] memory _epochGroup) public { claimRewardsMaster(_epochGroup, feeHandlersList); } /** * @dev Claims rewards for a given group of epochs and a given group of feeHandlers, distribute fees and its share to poolMaster * @param _epochGroup An array of epochs for which rewards are being claimed. Asc order and uniqueness is required. * @param _feeHandlerGroup An array of FeeHandlers for which rewards are being claimed. */ function claimRewardsMaster( uint256[] memory _epochGroup, address[] memory _feeHandlerGroup ) public { require(_epochGroup.length > 0, "cRMaster: _epochGroup required"); require( isOrderedSet(_epochGroup), "cRMaster: order and uniqueness required" ); require( _feeHandlerGroup.length > 0, "cRMaster: _feeHandlerGroup required" ); uint256[] memory accruedByFeeHandler = new uint256[]( _feeHandlerGroup.length ); uint256 feeId = 0; for (uint256 j = 0; j < _epochGroup.length; j++) { uint256 _epoch = _epochGroup[j]; feeId = getEpochDFeeDataId(_epoch, feeId); DFeeData storage epochDFee = delegationFees[feeId]; if (!epochDFee.applied) { applyFee(epochDFee); } (uint256 stake, uint256 delegatedStake, ) = kyberStaking .getStakerRawData(address(this), _epoch); for (uint256 i = 0; i < _feeHandlerGroup.length; i++) { RewardInfo memory rewardInfo = _claimRewardsFromKyber( _epoch, _feeHandlerGroup[i], epochDFee, stake, delegatedStake ); if (rewardInfo.totalRewards == 0) { continue; } accruedByFeeHandler[i] = accruedByFeeHandler[i].add( rewardInfo.poolMasterShare ); if (!successfulClaimByFeeHandler[_feeHandlerGroup[i]]) { successfulClaimByFeeHandler[_feeHandlerGroup[i]] = true; } } } address poolMaster = owner(); for (uint256 k = 0; k < accruedByFeeHandler.length; k++) { _sendTokens( rewardTokenByFeeHandler[_feeHandlerGroup[k]], poolMaster, accruedByFeeHandler[k], "cRMaster: poolMaster share transfer failed" ); } } function _claimRewardsFromKyber( uint256 _epoch, address _feeHandlerAddress, DFeeData memory epochDFee, uint256 stake, uint256 delegatedStake ) internal returns (RewardInfo memory rewardInfo) { rewardInfo.kyberFeeHandler = IExtendedKyberFeeHandler( _feeHandlerAddress ); uint256 unclaimed = getUnclaimedRewards( _epoch, rewardInfo.kyberFeeHandler ); if (unclaimed > 0) { rewardInfo .rewardToken = rewardTokenByFeeHandler[_feeHandlerAddress]; rewardInfo.kyberFeeHandler.claimStakerReward(address(this), _epoch); rewardInfo.totalRewards = unclaimed; rewardInfo.totalFee = rewardInfo .totalRewards .mul(epochDFee.fee) .div(MAX_DELEGATION_FEE); rewardInfo.rewardsAfterFee = rewardInfo.totalRewards.sub( rewardInfo.totalFee ); rewardInfo.poolMembersShare = calculateRewardsShare( delegatedStake, stake.add(delegatedStake), rewardInfo.rewardsAfterFee ); rewardInfo.poolMasterShare = rewardInfo.totalRewards.sub( rewardInfo.poolMembersShare ); // fee + poolMaster stake share epochFeeHandlerClaims[_epoch][_feeHandlerAddress] = Claim( true, rewardInfo.poolMembersShare, delegatedStake ); emit MasterClaimReward( _epoch, _feeHandlerAddress, payable(owner()), rewardInfo.rewardToken, rewardInfo.totalRewards, epochDFee.fee, rewardInfo.totalFee, rewardInfo.poolMasterShare.sub(rewardInfo.totalFee) ); } } /** * @dev Helper method to transfer tokens * @param _token address of the token * @param _receiver account that will receive the transfer * @param _value the amount of tokens to transfer * @param _errorMsg error msg in case transfer of native tokens fails */ function _sendTokens( IERC20 _token, address _receiver, uint256 _value, string memory _errorMsg ) internal { if (_value == 0) { return; } if (_token == ETH_TOKEN_ADDRESS) { (bool success, ) = _receiver.call{value: _value}(""); require(success, _errorMsg); } else { SafeERC20.safeTransfer(_token, _receiver, _value); } } /** * @dev Queries the amount of unclaimed rewards for the pool member in a given epoch and feeHandler * return 0 if PoolMaster has not called claimRewardMaster * return 0 if PoolMember has previously claimed reward for the epoch * return 0 if PoolMember has not stake for the epoch * return 0 if PoolMember has not delegated it stake to this contract for the epoch * @param _poolMember address of pool member * @param _epoch for which epoch the member is querying unclaimed reward * @param _feeHandler FeeHandler address */ function getUnclaimedRewardsMember( address _poolMember, uint256 _epoch, address _feeHandler ) public view returns (uint256) { if ( !epochFeeHandlerClaims[_epoch][address(_feeHandler)].claimedByPool ) { return 0; } if (claimedDelegateReward[_epoch][_poolMember][_feeHandler]) { return 0; } (uint256 stake, , address representative) = kyberStaking.getStakerData( _poolMember, _epoch ); if (stake == 0) { return 0; } if (representative != address(this)) { return 0; } Claim memory rewardForEpoch = epochFeeHandlerClaims[_epoch][_feeHandler]; return calculateRewardsShare( stake, rewardForEpoch.totalStaked, rewardForEpoch.totalRewards ); } /** * @dev Returns data related to all epochs and feeHandlers with unclaimed rewards, for a the poolMember. From initial to current epoch. * @param _poolMember address of pool member */ function getAllUnclaimedRewardsDataMember(address _poolMember) external view returns (UnclaimedRewardData[] memory) { uint256 currentEpoch = kyberDao.getCurrentEpochNumber(); return _getAllUnclaimedRewardsDataMember( _poolMember, firstEpoch, currentEpoch ); } /** * @dev Returns data related to all epochs and feeHandlers with unclaimed rewards, for a the poolMember. * @param _poolMember address of pool member * @param _fromEpoch initial epoch parameter * @param _toEpoch end epoch parameter */ function getAllUnclaimedRewardsDataMember( address _poolMember, uint256 _fromEpoch, uint256 _toEpoch ) external view returns (UnclaimedRewardData[] memory) { return _getAllUnclaimedRewardsDataMember( _poolMember, _fromEpoch, _toEpoch ); } /** * @dev Queries data related to epochs and feeHandlers with unclaimed rewards, for a the poolMember * @param _poolMember address of pool member * @param _fromEpoch initial epoch parameter * @param _toEpoch end epoch parameter */ function _getAllUnclaimedRewardsDataMember( address _poolMember, uint256 _fromEpoch, uint256 _toEpoch ) internal view returns (UnclaimedRewardData[] memory) { uint256 maxEpochNumber = _toEpoch.sub(_fromEpoch).add(1); uint256[] memory epochGroup = new uint256[](maxEpochNumber); uint256 e = 0; for (uint256 epoch = _fromEpoch; epoch <= _toEpoch; epoch++) { epochGroup[e] = epoch; e++; } return _getUnclaimedRewardsDataMember( _poolMember, epochGroup, feeHandlersList ); } function _getUnclaimedRewardsDataMember( address _poolMember, uint256[] memory _epochGroup, address[] memory _feeHandlerGroup ) internal view returns (UnclaimedRewardData[] memory) { UnclaimedRewardData[] memory epochFeeHanlderRewards = new UnclaimedRewardData[]( _epochGroup.length.mul(_feeHandlerGroup.length) ); uint256 rewardsCounter = 0; for (uint256 e = 0; e < _epochGroup.length; e++) { for (uint256 f = 0; f < _feeHandlerGroup.length; f++) { uint256 unclaimed = getUnclaimedRewardsMember( _poolMember, _epochGroup[e], _feeHandlerGroup[f] ); if (unclaimed > 0) { epochFeeHanlderRewards[rewardsCounter] = UnclaimedRewardData( _epochGroup[e], _feeHandlerGroup[f], unclaimed, rewardTokenByFeeHandler[_feeHandlerGroup[f]] ); rewardsCounter++; } } } UnclaimedRewardData[] memory result = new UnclaimedRewardData[]( rewardsCounter ); for (uint256 i = 0; i < (rewardsCounter); i++) { result[i] = epochFeeHanlderRewards[i]; } return result; } /** * @dev Someone claims rewards for a PoolMember in a given group of epochs in all feeHandlers. * It will transfer rewards where epoch->feeHandler has been claimed by the pool and not yet by the member. * This contract will keep locked remainings from rounding at a wei level. * @param _epochGroup An array of epochs for which rewards are being claimed * @param _poolMember PoolMember address to claim rewards for */ function claimRewardsMember( address _poolMember, uint256[] memory _epochGroup ) public { _claimRewardsMember(_poolMember, _epochGroup, feeHandlersList); } /** * @dev Someone claims rewards for a PoolMember in a given group of epochs in a given group of feeHandlers. * It will transfer rewards where epoch->feeHandler has been claimed by the pool and not yet by the member. * This contract will keep locked remainings from rounding at a wei level. * @param _epochGroup An array of epochs for which rewards are being claimed * @param _feeHandlerGroup An array of FeeHandlers for which rewards are being claimed * @param _poolMember PoolMember address to claim rewards for */ function claimRewardsMember( address _poolMember, uint256[] memory _epochGroup, address[] memory _feeHandlerGroup ) public { _claimRewardsMember(_poolMember, _epochGroup, _feeHandlerGroup); } function _claimRewardsMember( address _poolMember, uint256[] memory _epochGroup, address[] memory _feeHandlerGroup ) internal { require(_epochGroup.length > 0, "cRMember: _epochGroup required"); require( _feeHandlerGroup.length > 0, "cRMember: _feeHandlerGroup required" ); uint256[] memory accruedByFeeHandler = new uint256[]( _feeHandlerGroup.length ); for (uint256 j = 0; j < _epochGroup.length; j++) { uint256 _epoch = _epochGroup[j]; for (uint256 i = 0; i < _feeHandlerGroup.length; i++) { uint256 poolMemberShare = getUnclaimedRewardsMember( _poolMember, _epoch, _feeHandlerGroup[i] ); IERC20 rewardToken = rewardTokenByFeeHandler[_feeHandlerGroup[i]]; if (poolMemberShare == 0) { continue; } accruedByFeeHandler[i] = accruedByFeeHandler[i].add( poolMemberShare ); claimedDelegateReward[_epoch][_poolMember][_feeHandlerGroup[i]] = true; emit MemberClaimReward( _epoch, _poolMember, _feeHandlerGroup[i], rewardToken, poolMemberShare ); } } // distribute _poolMember rewards share for (uint256 k = 0; k < accruedByFeeHandler.length; k++) { _sendTokens( rewardTokenByFeeHandler[_feeHandlerGroup[k]], _poolMember, accruedByFeeHandler[k], "cRMember: poolMember share transfer failed" ); } } // Utils /** * @dev Calculates rewards share based on the stake over the total stake */ function calculateRewardsShare( uint256 stake, uint256 totalStake, uint256 rewards ) internal pure returns (uint256) { return stake.mul(rewards).div(totalStake); } /** * @dev Queries the number of elements in delegationFees */ function delegationFeesLength() public view returns (uint256) { return delegationFees.length; } /** * @dev Queries the number of elements in feeHandlersList */ function feeHandlersListLength() public view returns (uint256) { return feeHandlersList.length; } /** * @dev Checks if elements in array are ordered and unique */ function isOrderedSet(uint256[] memory numbers) internal pure returns (bool) { bool isOrdered = true; if (numbers.length > 1) { for (uint256 i = 0; i < numbers.length - 1; i++) { // strict inequality ensures both ordering and uniqueness if (numbers[i] >= numbers[i + 1]) { isOrdered = false; break; } } } return isOrdered; } /** * @dev Enables the contract to receive ETH */ receive() external payable { require( rewardTokenByFeeHandler[msg.sender] == ETH_TOKEN_ADDRESS, "only accept ETH from a KyberFeeHandler" ); } }
Applies a pending fee fee to be applied/
function applyFee(DFeeData storage fee) internal { fee.applied = true; emit NewFees(fee.fromEpoch, fee.fee); }
1,739,418
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma abicoder v2; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; } /** * @title UZPreSaleVesting * @author Unizen * @notice Presale distribution contract, that also allows claiming * all of the rewards of the whole quarter, as holder tokens. These can be * swapped 1 : 1 for an already vested amount of the final reward token. * This is relevant, since holder tokens can be staked, just as the real token * so the early investors don't lose out on an important benefit. **/ contract UZPreSaleVesting is Initializable, OwnableUpgradeable, PausableUpgradeable { using SafeERC20 for IERC20; using SafeERC20 for IERC20Burnable; using SafeMath for uint256; struct UserData { // users total utility tokens uint256 totalRewards; // used to store pending rewards // if a date needs to be adjusted uint256 savedRewards; // already claimed rewards uint256 claimedRewards; // tranches of holder tokens claimed uint8 claimedTranches; } // user data for stakers mapping(address => UserData) public _userData; // the actual token, that will be vested IERC20 public utilityToken; // the non transferable holder token IERC20Burnable public holderToken; // blockHeights of the distributions tranches uint256[] public _tranches; // amount of blocks per tranche uint256 public _trancheDuration; // safety guard in case somethings goes wrong // the contract can be halted bool internal _locked; function initialize( uint256 startBlock, uint256 duration, address rewardToken, address swapToken ) public virtual initializer { __Ownable_init(); __Pausable_init(); utilityToken = IERC20(rewardToken); holderToken = IERC20Burnable(swapToken); _calculateTranches(startBlock, duration); // 1 tranches _locked = false; } /* view functions */ /** * @dev Returns current vested amount of utility tokens * @return pendingRewards amount of accrued / swappable utility tokens **/ function getPendingUtilityTokens() external view returns (uint256 pendingRewards) { pendingRewards = _getPendingUtilityTokens(_msgSender()); } /** * @dev Returns the amount of accrued holder tokens for the current user * @return pendingHolderTokens amount of accrued / claimable holder tokens * @return tranches amount of claimable trances (max 3) **/ function getPendingHolderTokens() public view returns (uint256 pendingHolderTokens, uint8 tranches) { // return 0 if tranches are not set or first tranche is still in the future if (_tranches[0] == 0 || _tranches[0] >= block.number) return (0, 0); // fetch users data UserData storage user = _userData[_msgSender()]; // if user has no rewards assigned, return 0 if (_userData[_msgSender()].totalRewards == 0) return (0, 0); // calculate the amount of holder tokens per tranche uint256 trancheAmount = user.totalRewards.div(_tranches.length); // check every tranch if it can be claimed for (uint256 i = 0; i < _tranches.length; i++) { // tranches start block needs to be in the bast and needs to be unclaimed if (block.number > _tranches[i] && user.claimedTranches <= i) { // increase the amount of pending holder tokens pendingHolderTokens = pendingHolderTokens.add(trancheAmount); // increase the amount of pending tranches tranches++; } } } /** * @dev Helper function to check if a user is eligible for pre sale vesting * @param user address to check for eligibility * @return bool returns true if eligible **/ function isUserEligible(address user) external view returns (bool) { return (_userData[user].totalRewards > 0); } /** * @dev Convenience function to check the block number for the next tranche * @return tranche block.number of the start of this tranche. 0 if finished **/ function getNextHolderTokenTranche() external view returns (uint256 tranche) { for (uint256 i = 0; i < _tranches.length; i++) { if (block.number < _tranches[i]) return _tranches[i]; } return 0; } /** * @dev Returns whether the contract is currently locked * @return bool Return value is true, if the contract is locked **/ function getLocked() public view returns (bool) { return _locked; } /* mutating functions */ /** * @dev Claim all pending holder tokens for the requesting user **/ function claimHolderTokens() external whenNotPaused notLocked { require(_userData[msg.sender].totalRewards > 0, "NOT_WHITELISTED"); // fetch pending holder tokens (uint256 pendingRewards, uint8 tranches) = getPendingHolderTokens(); // return if none exist require(pendingRewards > 0, "NO_PENDING_REWARDS"); // check that the contract has sufficient holder tokens to send require( holderToken.balanceOf(address(this)) >= pendingRewards, "EXCEEDS_AVAIL_HT" ); // update user data with the amount of claimed tranches _userData[_msgSender()].claimedTranches = _userData[_msgSender()].claimedTranches + tranches; // sent holder tokens to user holderToken.safeTransfer(_msgSender(), pendingRewards); } /** * @dev Swaps desired `amount` of holder tokens to utility tokens. The amount * cannot exceed the users current pending / accrued utility tokens. * Holder tokens will be burned in the process and swap is always 1:1 * @param amount Amount of holder tokens to be swapped to utility tokens */ function swapHolderTokensForUtility(uint256 amount) external whenNotPaused notLocked { require(_userData[msg.sender].totalRewards > 0, "NOT_WHITELISTED"); // fetch pending utility tokens uint256 pendingRewards = _getPendingUtilityTokens(_msgSender()); // return if no utility tokens are ready to be vested require(pendingRewards > 0, "NO_PENDING_REWARDS"); // currently vested utility tokens are the maximum to be swapped // return if the desired amount exceeds the currently vested utility tokens require(pendingRewards >= amount, "AMOUNT_EXCEEDS_REWARDS"); // check that the contract has sufficient utility tokens to send require( utilityToken.balanceOf(address(this)) >= amount, "EXCEEDS_AVAILABLE_TOKENS" ); // update users claimed amount of utility tokens. these will be removed from the // pending tokens _userData[_msgSender()].claimedRewards = _userData[_msgSender()] .claimedRewards .add(amount); // transfer holder tokens from user to contract holderToken.safeTransferFrom(_msgSender(), address(this), amount); // burn holder tokens holderToken.burn(amount); // send same amount of utility tokens to user utilityToken.safeTransfer(_msgSender(), amount); } /* internal functions */ /** * @dev This function will calculate the start blocks for each tranche * @param startBlock start of the vesting contract * @param duration Amount of blocks per tranche*/ function _calculateTranches(uint256 startBlock, uint256 duration) internal { // start block cannot be 0 require(startBlock > 0, "NO_START_BLOCK"); // duration of tranches needs to be bigger than 0 require(duration > 0, "NO_DURATION"); // set tranche duration _trancheDuration = duration; // tranche 1 starts at start _tranches.push(startBlock); // 1tranches only } /** * @dev The actual internal function that is used to calculate the accrued * utility tokens, ready for vesting of a user * @param user the address to check for pending utility tokens * @return pendingRewards amount of accrued utility tokens up to the current block **/ function _getPendingUtilityTokens(address user) internal view returns (uint256 pendingRewards) { // return 0 if tranches are not set or first tranche is still in the future if (_tranches[0] == 0 || _tranches[0] >= block.number) return 0; // fetch users data UserData storage userData = _userData[user]; // if user has no rewards assigned, return 0 if (userData.totalRewards == 0) return 0; // calculate the multiplier, used to calculate the accrued utility tokens // from start of vesting to current block uint256 multiplier = block.number.sub(_tranches[0]); // calculate the maximal multiplier, to be used as threshold, so we // don't calculate more rewards, after vesting end reached uint256 maxDuration = _trancheDuration.mul(_tranches.length); // use multiplier if it no exceeds maximum. otherwise use max multiplier multiplier = (multiplier <= maxDuration) ? multiplier : maxDuration; // calculate the users pending / accrued utility tokens // based on users rewards per block and the given multiplier. // remove already claimed rewards by swapping holder tokens // for utility tokens uint256 rewardsPerBlock = userData.totalRewards.div(maxDuration); uint256 totalReward = multiplier.mul(rewardsPerBlock).add( userData.savedRewards ); pendingRewards = totalReward.sub(userData.claimedRewards); } /* control functions */ /** * @dev Convenience function to add a list of users to be eligible for vesting * @param users list of addresses for eligible users * @param rewards list of total rewards for the users **/ function addMultipleUserVestings( address[] calldata users, uint256[] calldata rewards ) external onlyOwner { // check that user array is not empty require(users.length > 0, "NO_USERS"); // check that rewards array is not empty require(rewards.length > 0, "NO_VESTING_DATA"); // check that user and reward array a equal length require(users.length == rewards.length, "PARAM_NOT_EQ_LENGTH"); // loop through the list and call the default function to add new vestings for (uint8 i = 0; i < users.length; i++) { addUserVesting(users[i], rewards[i]); } } /** * @dev Adds a new user eligible for vesting. Automatically calculates rewardsPerBlock, * based on the tranches and tranche duration * @param user address of eligible user * @param totalRewards amount of rewards to be vested for this user **/ function addUserVesting(address user, uint256 totalRewards) public onlyOwner { // check that address is not empty require(user != address(0), "ZERO_ADDRESS"); // check that user has rewards to receive require(totalRewards > 0, "NO_REWARDS"); // check that user does not exist yet require(_userData[user].totalRewards == 0, "EXISTING_USER"); // start block is start of tranche one uint256 startBlock = _tranches[0]; // end block is tranche three + tranche duration uint256 endBlock = _tranches[_tranches.length - 1].add( _trancheDuration ); // check that current block is still below end of vesting // require(block.number < endBlock, "VESTING_FINISHED"); // make sure that start block is smaller than end block // require(endBlock > startBlock, "INVALID_START_BLOCK"); // create user data object UserData memory newUserData; newUserData.totalRewards = totalRewards; _userData[user] = newUserData; } /** * @dev should allow contract's owner add more tranches * @param _tranchesAmount amount of tranches want to add: 1, 2, 3 ... */ function addTranches(uint256 _tranchesAmount) external onlyOwner { uint256 lastTranches = _tranches[_tranches.length - 1]; for (uint256 i = 0; i < _tranchesAmount; i++) { _tranches.push(lastTranches.add(_trancheDuration)); lastTranches = _tranches[_tranches.length - 1]; } } /** * @dev pause smart contract */ function pause() public onlyOwner { _pause(); } /** * @dev unpause smart contract */ function unPause() public onlyOwner { _unpause(); } function emergencyWithDrawToken(address token, address to) external whenPaused onlyOwner { uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(to, balance); } /** * @dev Remove eligibility of a user. Either deactivate completely or optionally leave the already * accrued utility tokens up for claiming, but do not accrue any further tokens. * @param user Address of the user to remove * @param keepVestedTokens If true, the user will still be able to claim / swap already accrued token rewards. But won't accrue more. **/ function removeUserVesting(address user, bool keepVestedTokens) external onlyOwner { // check that user address is not empty require(user != address(0), "ADDRESS_ZERO"); // check that user is existing and currently eligible require(_userData[user].totalRewards > 0, "INVALID_USER"); // fetch user data UserData storage userData = _userData[user]; // store users pending / accrued rewards, if `keepVestedTokens` is true. Otherwise set to zero userData.savedRewards = (keepVestedTokens == true) ? userData.savedRewards.add(_getPendingUtilityTokens(user)) : 0; // set users total rewards to users saved rewards, if `keepVestedTokens` is true. Otherwise set to zero userData.totalRewards = (keepVestedTokens == true) ? userData.savedRewards.add(userData.claimedRewards) : 0; } function setLocked(bool locked) external onlyOwner { require(locked != _locked, "SAME_VALUE"); _locked = locked; } function setDuration(uint256 _newDuration) external onlyOwner { _trancheDuration = _newDuration; } /* modifiers */ modifier notLocked() { require(_locked == false, "LOCKED"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
control functions / Convenience function to add a list of users to be eligible for vesting users list of addresses for eligible users rewards list of total rewards for the users/ check that user array is not empty check that rewards array is not empty check that user and reward array a equal length loop through the list and call the default function to add new vestings
function addMultipleUserVestings( address[] calldata users, uint256[] calldata rewards ) external onlyOwner { require(users.length > 0, "NO_USERS"); require(rewards.length > 0, "NO_VESTING_DATA"); require(users.length == rewards.length, "PARAM_NOT_EQ_LENGTH"); for (uint8 i = 0; i < users.length; i++) { addUserVesting(users[i], rewards[i]); } }
355,110
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "../interfaces/IBentoBoxMinimal.sol"; import "../interfaces/IMasterDeployer.sol"; import "../TridentRouter.sol"; import "./TridentPermit.sol"; /// @notice Trident router helper contract. contract RouterHelper is TridentPermit { /// @notice BentoBox token vault. IBentoBoxMinimal public immutable bento; /// @notice Trident AMM master deployer contract. IMasterDeployer public immutable masterDeployer; /// @notice ERC-20 token for wrapped ETH (v9). address internal immutable wETH; /// @notice The user should use 0x0 if they want to deposit ETH address constant USE_ETHEREUM = address(0); constructor( IBentoBoxMinimal _bento, IMasterDeployer _masterDeployer, address _wETH ) { bento = _bento; masterDeployer = _masterDeployer; wETH = _wETH; _bento.registerProtocol(); } /// @notice Provides batch function calls for this contract and returns the data from all of them if they all succeed. /// Adapted from https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/base/Multicall.sol, License-Identifier: GPL-2.0-or-later. /// @dev The `msg.value` should not be trusted for any method callable from this function. /// @dev Uses a modified version of the batch function - preventing multiple calls of the single input swap functions /// @param data ABI-encoded params for each of the calls to make to this contract. /// @return results The results from each of the calls passed in via `data`. function batch(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); // We only allow one exactInputSingle call to be made in a single batch call. // This is not really needed but we want to save users from signing malicious payloads. // We also don't want nested batch calls. bool swapCalled; for (uint256 i = 0; i < data.length; i++) { bytes4 selector = getSelector(data[i]); if (selector == TridentRouter.exactInputSingle.selector || selector == TridentRouter.exactInputSingleWithNativeToken.selector) { require(!swapCalled, "Swap called twice"); swapCalled = true; } else { require(selector != this.batch.selector, "Nested Batch"); } (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577. if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } function deployPool(address factory, bytes calldata deployData) external payable returns (address) { return masterDeployer.deployPool(factory, deployData); } /// @notice Helper function to allow batching of BentoBox master contract approvals so the first trade can happen in one transaction. function approveMasterContract( uint8 v, bytes32 r, bytes32 s ) external payable { bento.setMasterContractApproval(msg.sender, address(this), true, v, r, s); } /// @notice Provides gas-optimized balance check on this contract to avoid redundant extcodesize check in addition to returndatasize check. /// @param token Address of ERC-20 token. /// @return balance Token amount held by this contract. function balanceOfThis(address token) internal view returns (uint256 balance) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this))); // @dev balanceOf(address). require(success && data.length >= 32, "BALANCE_OF_FAILED"); balance = abi.decode(data, (uint256)); } /// @notice Provides 'safe' ERC-20 {transfer} for tokens that don't consistently return true/false. /// @param token Address of ERC-20 token. /// @param recipient Account to send tokens to. /// @param amount Token amount to send. function safeTransfer( address token, address recipient, uint256 amount ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, recipient, amount)); // @dev transfer(address,uint256). require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); } /// @notice Provides 'safe' ERC-20 {transferFrom} for tokens that don't consistently return true/false. /// @param token Address of ERC-20 token. /// @param sender Account to send tokens from. /// @param recipient Account to send tokens to. /// @param amount Token amount to send. function safeTransferFrom( address token, address sender, address recipient, uint256 amount ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, sender, recipient, amount)); // @dev transferFrom(address,address,uint256). require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED"); } /// @notice Provides low-level `wETH` {withdraw}. /// @param amount Token amount to unwrap into ETH. function withdrawFromWETH(uint256 amount) internal { (bool success, ) = wETH.call(abi.encodeWithSelector(0x2e1a7d4d, amount)); // @dev withdraw(uint256). require(success, "WITHDRAW_FROM_WETH_FAILED"); } /// @notice Provides 'safe' ETH transfer. /// @param recipient Account to send ETH to. /// @param amount ETH amount to send. function safeTransferETH(address recipient, uint256 amount) internal { (bool success, ) = recipient.call{value: amount}(""); require(success, "ETH_TRANSFER_FAILED"); } /** * @notice function to extract the selector of a bytes calldata * @param _data the calldata bytes */ function getSelector(bytes memory _data) internal pure returns (bytes4 sig) { assembly { sig := mload(add(_data, 32)) } } }
Provides 'safe' ERC-20 {transfer} for tokens that don't consistently return true/false. token Address of ERC-20 token. recipient Account to send tokens to. amount Token amount to send.
function safeTransfer( address token, address recipient, uint256 amount ) internal { require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); }
1,086,564
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../../openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./GovernorAlpha.sol"; import "./RewardDistribution.sol"; contract LpGovernor is Initializable, ContextUpgradeable, ERC20Upgradeable, GovernorAlpha, RewardDistribution { // admin: to mint/burn token address internal _minter; /** * @notice Initialize LpGovernor instance. * * @param name ERC20 name of token. * @param symbol ERC20 symbol of token. * @param minter The role that has privilege to mint / burn token. * @param target The target of execution, all action of proposal will be send to target. * @param rewardToken The ERC20 token used as reward of mining / reward distribution. * @param poolCreator The address of pool creator, whose owner will be the owner of governor. */ function initialize( string memory name, string memory symbol, address minter, address target, address rewardToken, address poolCreator ) public virtual initializer { __ERC20_init_unchained(name, symbol); __GovernorAlpha_init_unchained(target); __RewardDistribution_init_unchained(rewardToken, poolCreator); _minter = minter; _target = target; } function getMinter() public view returns (address) { return _minter; } /** * @notice Mint token to account. */ function mint(address account, uint256 amount) public virtual { require(_msgSender() == _minter, "must be minter to mint"); _mint(account, amount); } /** * @notice Burn token from account. Voting will block also block burning. */ function burn(address account, uint256 amount) public virtual { require(_msgSender() == _minter, "must be minter to burn"); _burn(account, amount); } function isLocked(address account) public virtual returns (bool) { return GovernorAlpha.isLockedByVoting(account); } /** * @notice Override ERC20 balanceOf. */ function balanceOf(address account) public view virtual override(ERC20Upgradeable, GovernorAlpha, RewardDistribution) returns (uint256) { return ERC20Upgradeable.balanceOf(account); } /** * @notice Override ERC20 balanceOf. */ function totalSupply() public view virtual override(ERC20Upgradeable, GovernorAlpha, RewardDistribution) returns (uint256) { return ERC20Upgradeable.totalSupply(); } function _beforeTokenTransfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isLocked(sender), "sender is locked"); _updateReward(sender); _updateReward(recipient); super._beforeTokenTransfer(sender, recipient, amount); } bytes32[50] private __gap; }
Burn token from account. Voting will block also block burning./
function burn(address account, uint256 amount) public virtual { require(_msgSender() == _minter, "must be minter to burn"); _burn(account, amount); }
1,771,279
pragma solidity ^0.5.8; contract ERC20Interface { function NAME619() public view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL529() public view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS264() public view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY200() public view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF986(address tokenOwner) public view returns (uint balance); //inject NONSTANDARD NAMING function ALLOWANCE990(address tokenOwner, address spender) public view returns (uint remaining); //inject NONSTANDARD NAMING function TRANSFER909(address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function APPROVE745(address spender, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM849(address from, address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function BURN943(uint256 amount) public; //inject NONSTANDARD NAMING event TRANSFER421(address indexed from, address indexed to, uint tokens); //inject NONSTANDARD NAMING event APPROVAL99(address indexed tokenOwner, address indexed spender, uint tokens); //inject NONSTANDARD NAMING } contract MerkleDrop { bytes32 public root; ERC20Interface public droppedToken; uint public decayStartTime; uint public decayDurationInSeconds; uint public initialBalance; uint public remainingValue; // The total of not withdrawn entitlements, not considering decay uint public spentTokens; // The total tokens spent by the contract, burnt or withdrawn mapping (address => bool) public withdrawn; event WITHDRAW776(address recipient, uint value, uint originalValue); //inject NONSTANDARD NAMING event BURN575(uint value); //inject NONSTANDARD NAMING constructor(ERC20Interface _droppedToken, uint _initialBalance, bytes32 _root, uint _decayStartTime, uint _decayDurationInSeconds) public { // The _initialBalance should be equal to the sum of airdropped tokens droppedToken = _droppedToken; initialBalance = _initialBalance; remainingValue = _initialBalance; root = _root; decayStartTime = _decayStartTime; decayDurationInSeconds = _decayDurationInSeconds; } function WITHDRAW337(uint value, bytes32[] memory proof) public { //inject NONSTANDARD NAMING require(VERIFYENTITLED968(msg.sender, value, proof), "The proof could not be verified."); require(! withdrawn[msg.sender], "You have already withdrawn your entitled token."); BURNUNUSABLETOKENS848(); uint valueToSend = DECAYEDENTITLEMENTATTIME410(value, now, false); assert(valueToSend <= value); require(droppedToken.BALANCEOF986(address(this)) >= valueToSend, "The MerkleDrop does not have tokens to drop yet / anymore."); require(valueToSend != 0, "The decayed entitled value is now zero."); withdrawn[msg.sender] = true; remainingValue -= value; spentTokens += valueToSend; require(droppedToken.TRANSFER909(msg.sender, valueToSend)); emit WITHDRAW776(msg.sender, valueToSend, value); } function VERIFYENTITLED968(address recipient, uint value, bytes32[] memory proof) public view returns (bool) { //inject NONSTANDARD NAMING // We need to pack the 20 bytes address to the 32 bytes value // to match with the proof made with the python merkle-drop package bytes32 leaf = keccak256(abi.encodePacked(recipient, value)); return VERIFYPROOF104(leaf, proof); } function DECAYEDENTITLEMENTATTIME410(uint value, uint time, bool roundUp) public view returns (uint) { //inject NONSTANDARD NAMING if (time <= decayStartTime) { return value; } else if (time >= decayStartTime + decayDurationInSeconds) { return 0; } else { uint timeDecayed = time - decayStartTime; uint valueDecay = DECAY452(value, timeDecayed, decayDurationInSeconds, !roundUp); assert(valueDecay <= value); return value - valueDecay; } } function BURNUNUSABLETOKENS848() public { //inject NONSTANDARD NAMING if (now <= decayStartTime) { return; } // The amount of tokens that should be held within the contract after burning uint targetBalance = DECAYEDENTITLEMENTATTIME410(remainingValue, now, true); // toBurn = (initial balance - target balance) - what we already removed from initial balance uint currentBalance = initialBalance - spentTokens; assert(targetBalance <= currentBalance); uint toBurn = currentBalance - targetBalance; spentTokens += toBurn; BURN943(toBurn); } function DELETECONTRACT939() public { //inject NONSTANDARD NAMING require(now >= decayStartTime + decayDurationInSeconds, "The storage cannot be deleted before the end of the merkle drop."); BURNUNUSABLETOKENS848(); selfdestruct(address(0)); } function VERIFYPROOF104(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 currentHash = leaf; for (uint i = 0; i < proof.length; i += 1) { currentHash = PARENTHASH659(currentHash, proof[i]); } return currentHash == root; } function PARENTHASH659(bytes32 a, bytes32 b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING if (a < b) { return keccak256(abi.encode(a, b)); } else { return keccak256(abi.encode(b, a)); } } function BURN943(uint value) internal { //inject NONSTANDARD NAMING if (value == 0) { return; } emit BURN575(value); droppedToken.BURN943(value); } function DECAY452(uint value, uint timeToDecay, uint totalDecayTime, bool roundUp) internal pure returns (uint) { //inject NONSTANDARD NAMING uint decay; if (roundUp) { decay = (value*timeToDecay+totalDecayTime-1)/totalDecayTime; } else { decay = value*timeToDecay/totalDecayTime; } return decay >= value ? value : decay; } }
inject NONSTANDARD NAMING
function DECAYEDENTITLEMENTATTIME410(uint value, uint time, bool roundUp) public view returns (uint) {
12,727,509
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol"; import {CoreRef} from "../refs/CoreRef.sol"; import {ICore} from "../core/ICore.sol"; import {Core} from "../core/Core.sol"; import {TribeRoles} from "../core/TribeRoles.sol"; import {IPodAdminGateway} from "./interfaces/IPodAdminGateway.sol"; import {IPodFactory} from "./interfaces/IPodFactory.sol"; /// @title PodAdminGateway for TRIBE Governance pods /// @notice Acts as a gateway for admin functionality and vetos in the TRIBE governance pod system /// @dev Contract is intended to be set as the podAdmin for all deployed Orca pods. Specifically enables: /// 1. Adding a member to a pod /// 2. Removing a member from a pod /// 3. Transferring a pod member /// 4. Toggling a pod membership transfer switch /// 5. Vetoing a pod proposal contract PodAdminGateway is CoreRef, IPodAdminGateway { /// @notice Orca membership token for the pods. Handles permissioning pod members MemberToken private immutable memberToken; /// @notice Pod factory which creates optimistic pods and acts as a source of information IPodFactory public immutable podFactory; constructor( address _core, address _memberToken, address _podFactory ) CoreRef(_core) { memberToken = MemberToken(_memberToken); podFactory = IPodFactory(_podFactory); } //////////////////////// GETTERS //////////////////////////////// /// @notice Calculate the specific pod admin role identifier /// @dev This role is able to add pod members, remove pod members, lock and unlock transfers and veto /// proposals function getSpecificPodAdminRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_ADMIN")); } /// @notice Calculate the specific pod guardian role identifier /// @dev This role is able to remove pod members and veto pod proposals function getSpecificPodGuardianRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_GUARDIAN")); } ///////////////////////// ADMIN PRIVILEDGES //////////////////////////// /// @notice Admin functionality to add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADD_MEMBER_ROLE function addPodMember(uint256 _podId, address _member) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _addMemberToPod(_podId, _member); } /// @notice Internal method to add a member to a pod function _addMemberToPod(uint256 _podId, address _member) internal { emit AddPodMember(_podId, _member); memberToken.mint(_member, _podId, bytes("")); } /// @notice Admin functionality to batch add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADMIN_REMOVE_MEMBER function batchAddPodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _addMemberToPod(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to remove a member from a pod. /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function removePodMember(uint256 _podId, address _member) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { _removePodMember(_podId, _member); } /// @notice Internal method to remove a member from a pod function _removePodMember(uint256 _podId, address _member) internal { emit RemovePodMember(_podId, _member); memberToken.burn(_member, _podId); } /// @notice Admin functionality to batch remove a member from a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function batchRemovePodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _removePodMember(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to turn off pod membership transfer /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function lockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, true); } /// @notice Admin functionality to turn on pod membership transfers /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function unlockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, false); } /// @notice Internal method to toggle a pod membership transfer lock function _setMembershipTransferLock(uint256 _podId, bool _lock) internal { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); podController.setPodTransferLock(_podId, _lock); emit PodMembershipTransferLock(_podId, _lock); } /// @notice Transfer the admin of a pod to a new address /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function transferAdmin(uint256 _podId, address _newAdmin) external hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); address oldPodAdmin = podController.podAdmin(_podId); podController.updatePodAdmin(_podId, _newAdmin); emit UpdatePodAdmin(_podId, oldPodAdmin, _newAdmin); } /////////////// VETO CONTROLLER ///////////////// /// @notice Allow a proposal to be vetoed in a pod timelock /// @dev Permissioned to GOVERNOR, POD_VETO_ADMIN, GUARDIAN, POD_ADMIN and the specific /// pod admin and guardian roles function veto(uint256 _podId, bytes32 _proposalId) external override hasAnyOfSixRoles( TribeRoles.GOVERNOR, TribeRoles.POD_VETO_ADMIN, TribeRoles.GUARDIAN, TribeRoles.POD_ADMIN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { address _podTimelock = podFactory.getPodTimelock(_podId); emit VetoTimelock(_podId, _podTimelock, _proposalId); TimelockController(payable(_podTimelock)).cancel(_proposalId); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "./interfaces/IControllerRegistry.sol"; import "./interfaces/IControllerBase.sol"; contract MemberToken is ERC1155Supply, Ownable { using Address for address; IControllerRegistry public controllerRegistry; mapping(uint256 => address) public memberController; uint256 public nextAvailablePodId = 0; string public _contractURI = "https://orcaprotocol-nft.vercel.app/assets/contract-metadata"; event MigrateMemberController(uint256 podId, address newController); /** * @param _controllerRegistry The address of the ControllerRegistry contract */ constructor(address _controllerRegistry, string memory uri) ERC1155(uri) { require(_controllerRegistry != address(0), "Invalid address"); controllerRegistry = IControllerRegistry(_controllerRegistry); } // Provides metadata value for the opensea wallet. Must be set at construct time // Source: https://www.reddit.com/r/ethdev/comments/q4j5bf/contracturi_not_reflected_in_opensea/ function contractURI() public view returns (string memory) { return _contractURI; } // Note that OpenSea does not currently update contract metadata when this value is changed. - Nov 2021 function setContractURI(string memory newContractURI) public onlyOwner { _contractURI = newContractURI; } /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external { require(_newController != address(0), "Invalid address"); require( msg.sender == memberController[_podId], "Invalid migrate controller" ); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); memberController[_podId] = _newController; emit MigrateMemberController(_podId, _newController); } function getNextAvailablePodId() external view returns (uint256) { return nextAvailablePodId; } function setUri(string memory uri) external onlyOwner { _setURI(uri); } /** * @param _account The account address to assign the membership token to * @param _id The membership token id to mint * @param data Passes a flag for initial creation event */ function mint( address _account, uint256 _id, bytes memory data ) external { _mint(_account, _id, 1, data); } /** * @param _accounts The account addresses to assign the membership tokens to * @param _id The membership token id to mint * @param data Passes a flag for an initial creation event */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _mint(_accounts[index], _id, 1, data); } } /** * @param _accounts The account addresses to burn the membership tokens from * @param _id The membership token id to burn */ function burnSingleBatch(address[] memory _accounts, uint256 _id) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _burn(_accounts[index], _id, 1); } } function createPod(address[] memory _accounts, bytes memory data) external returns (uint256) { uint256 id = nextAvailablePodId; nextAvailablePodId += 1; require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); memberController[id] = msg.sender; if (_accounts.length != 0) { mintSingleBatch(_accounts, id, data); } return id; } /** * @param _account The account address holding the membership token to destroy * @param _id The id of the membership token to destroy */ function burn(address _account, uint256 _id) external { _burn(_account, _id, 1); } // this hook gets called before every token event including mint and burn /** * @param operator The account address that initiated the action * @param from The account address recieveing the membership token * @param to The account address sending the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Passes a flag for an initial creation event */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { // use first id to lookup controller address controller = memberController[ids[0]]; require(controller != address(0), "Pod doesn't exist"); for (uint256 i = 0; i < ids.length; i += 1) { // check if recipient is already member if (to != address(0)) { require(balanceOf(to, ids[i]) == 0, "User is already member"); } // verify all ids use same controller require( memberController[ids[i]] == controller, "Ids have different controllers" ); } // perform orca token transfer validations IControllerBase(controller).beforeTokenTransfer( operator, from, to, ids, amounts, data ); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IControllerV1.sol"; import "./interfaces/IMemberToken.sol"; import "./interfaces/IControllerRegistry.sol"; import "./SafeTeller.sol"; import "./ens/IPodEnsRegistrar.sol"; contract ControllerV1 is IControllerV1, SafeTeller, Ownable { event CreatePod(uint256 podId, address safe, address admin, string ensName); event UpdatePodAdmin(uint256 podId, address admin); IMemberToken public immutable memberToken; IControllerRegistry public immutable controllerRegistry; IPodEnsRegistrar public podEnsRegistrar; string public constant VERSION = "1.2.0"; mapping(address => uint256) public safeToPodId; mapping(uint256 => address) public podIdToSafe; mapping(uint256 => address) public podAdmin; mapping(uint256 => bool) public isTransferLocked; uint8 internal constant CREATE_EVENT = 0x01; /** * @dev Will instantiate safe teller with gnosis master and proxy addresses * @param _memberToken The address of the MemberToken contract * @param _controllerRegistry The address of the ControllerRegistry contract * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _memberToken, address _controllerRegistry, address _proxyFactoryAddress, address _gnosisMasterAddress, address _podEnsRegistrar, address _fallbackHandlerAddress ) SafeTeller( _proxyFactoryAddress, _gnosisMasterAddress, _fallbackHandlerAddress ) { require(_memberToken != address(0), "Invalid address"); require(_controllerRegistry != address(0), "Invalid address"); require(_proxyFactoryAddress != address(0), "Invalid address"); require(_gnosisMasterAddress != address(0), "Invalid address"); require(_podEnsRegistrar != address(0), "Invalid address"); require(_fallbackHandlerAddress != address(0), "Invalid address"); memberToken = IMemberToken(_memberToken); controllerRegistry = IControllerRegistry(_controllerRegistry); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } function updatePodEnsRegistrar(address _podEnsRegistrar) external override onlyOwner { require(_podEnsRegistrar != address(0), "Invalid address"); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { address safe = createSafe(_members, threshold); _createPod( _members, safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { require(_safe != address(0), "invalid safe address"); require(safeToPodId[_safe] == 0, "safe already in use"); require(isSafeModuleEnabled(_safe), "safe module must be enabled"); require( isSafeMember(_safe, msg.sender) || msg.sender == _safe, "caller must be safe or member" ); address[] memory members = getSafeMembers(_safe); _createPod( members, _safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @param _members The addresses of the members of the pod * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function _createPod( address[] memory _members, address _safe, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) private { // add create event flag to token data bytes memory data = new bytes(1); data[0] = bytes1(uint8(CREATE_EVENT)); uint256 podId = memberToken.createPod(_members, data); // The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID require(podId == expectedPodId, "pod id didn't match, try again"); emit CreatePod(podId, _safe, _admin, _ensString); emit UpdatePodAdmin(podId, _admin); if (_admin != address(0)) { // will lock safe modules if admin exists setModuleLock(_safe, true); podAdmin[podId] = _admin; } podIdToSafe[podId] = _safe; safeToPodId[_safe] = podId; // setup pod ENS address reverseRegistrar = podEnsRegistrar.registerPod( _label, _safe, msg.sender ); setupSafeReverseResolver(_safe, reverseRegistrar, _ensString); // Node is how ENS identifies names, we need that to setText bytes32 node = podEnsRegistrar.getEnsNode(_label); podEnsRegistrar.setText(node, "avatar", _imageUrl); podEnsRegistrar.setText(node, "podId", Strings.toString(podId)); } /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external override { require( msg.sender == podAdmin[_podId], "Must be admin to set module lock" ); setModuleLock(podIdToSafe[_podId], _isLocked); } /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require(safe != address(0), "Pod doesn't exist"); // if there is no admin it can only be added by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can add new admin"); } else { require(msg.sender == admin, "Only admin can update admin"); } // set module lock to true for non zero _newAdmin setModuleLock(safe, _newAdmin != address(0)); podAdmin[_podId] = _newAdmin; emit UpdatePodAdmin(_podId, _newAdmin); } /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; // if no pod admin it can only be set by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can set transfer lock"); } else { // if admin then it can be set by admin or safe require( msg.sender == admin || msg.sender == safe, "Only admin or safe can set transfer lock" ); } // set podid to transfer lock bool isTransferLocked[_podId] = _isTransferLocked; } /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external override { require(_newController != address(0), "Invalid address"); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require( msg.sender == admin || msg.sender == safe, "User not authorized" ); IControllerBase newController = IControllerBase(_newController); // nullify current pod state podAdmin[_podId] = address(0); podIdToSafe[_podId] = address(0); safeToPodId[safe] = 0; // update controller in MemberToken memberToken.migrateMemberController(_podId, _newController); // update safe module to _newController migrateSafeTeller(safe, _newController, _prevModule); // update pod state in _newController newController.updatePodState(_podId, admin, safe); } /** * @dev This is called by another version of controller to migrate a pod to this version * @dev Will only accept calls from registered controllers * @dev Can only be called once. * @param _podId The id number of the pod * @param _podAdmin The address of the pod admin * @param _safeAddress The address of the safe */ function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external override { require(_safeAddress != address(0), "Invalid address"); require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); require( podAdmin[_podId] == address(0) && podIdToSafe[_podId] == address(0) && safeToPodId[_safeAddress] == 0, "Pod already exists" ); // if there is a pod admin, set state and lock modules if (_podAdmin != address(0)) { podAdmin[_podId] = _podAdmin; setModuleLock(_safeAddress, true); } podIdToSafe[_podId] = _safeAddress; safeToPodId[_safeAddress] = _podId; setSafeTellerAsGuard(_safeAddress); emit UpdatePodAdmin(_podId, _podAdmin); } /** * @param operator The address that initiated the action * @param from The address sending the membership token * @param to The address recieveing the membership token * @param ids An array of membership token ids to be transfered * @param data Passes a flag for an initial creation event */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory, bytes memory data ) external override { require(msg.sender == address(memberToken), "Not Authorized"); // if create event than side effects have been pre-handled // only recognise data flags from this controller if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return; for (uint256 i = 0; i < ids.length; i += 1) { uint256 podId = ids[i]; address safe = podIdToSafe[podId]; address admin = podAdmin[podId]; if (from == address(0)) { // mint event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onMint(to, safe); } else if (to == address(0)) { // burn event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onBurn(from, safe); } else { // pod cannot be locked require( isTransferLocked[podId] == false, "Pod Is Transfer Locked" ); // transfer event onTransfer(from, to, safe); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (governance/TimelockController.sol) pragma solidity ^0.8.0; import "../access/AccessControl.sol"; import "../token/ERC721/IERC721Receiver.sol"; import "../token/ERC1155/IERC1155Receiver.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`, and a list of * initial proposers and executors. The proposers receive both the * proposer and the canceller role (for backward compatibility). The * executors receive the executor role. * * NOTE: At construction, both the deployer and the timelock itself are * administrators. This helps further configuration of the timelock by the * deployer. After configuration is done, it is recommended that the * deployer renounces its admin position and relies on timelocked * operations to perform future maintenance. */ constructor( uint256 minDelay, address[] memory proposers, address[] memory executors ) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers and cancellers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); _setupRole(CANCELLER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, payloads, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(id, predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], payloads[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { require(isOperationReady(id), "TimelockController: operation is not ready"); require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call( bytes32 id, uint256 index, address target, uint256 value, bytes calldata data ) private { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IFei private immutable _fei; IERC20 private immutable _tribe; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _fei = ICore(coreAddress).fei(); _tribe = ICore(coreAddress).tribe(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize(address) internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller"); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor"); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfSixRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5, bytes32 role6 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender) || _core.hasRole(role6, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyFei() { require(msg.sender == address(_fei), "CoreRef: Caller is not FEI"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _fei; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _tribe; } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return _fei.balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return _tribe.balanceOf(address(this)); } function _burnFeiHeld() internal { _fei.burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { _fei.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Permissions.sol"; import "./ICore.sol"; import "../fei/Fei.sol"; import "../tribe/Tribe.sol"; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury contract Core is ICore, Permissions, Initializable { /// @notice the address of the FEI contract IFei public override fei; /// @notice the address of the TRIBE contract IERC20 public override tribe; function init() external override initializer { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); _setFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); _setTribe(address(_tribe)); } /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external override onlyGovernor { _setFei(token); } /// @notice sets Tribe address to a new address /// @param token new tribe address function setTribe(address token) external override onlyGovernor { _setTribe(token); } /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint256 amount) external override onlyGovernor { IERC20 _tribe = tribe; require(_tribe.balanceOf(address(this)) >= amount, "Core: Not enough Tribe"); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } function _setFei(address token) internal { fei = IFei(token); emit FeiUpdate(token); } function _setTribe(address token) internal { tribe = IERC20(token); emit TribeUpdate(token); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /** @title Tribe DAO ACL Roles @notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO. Roles are broken up into 3 categories: * Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed. * Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms * Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs. */ library TribeRoles { /*/////////////////////////////////////////////////////////////// Major Roles //////////////////////////////////////////////////////////////*/ /// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality. bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE"); /// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE"); /// @notice the role which can arbitrarily move PCV in any size from any contract bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE"); /// @notice can mint FEI arbitrarily bytes32 internal constant MINTER = keccak256("MINTER_ROLE"); /// @notice Manages lower level - Admin and Minor - roles. Able to grant and revoke these bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); /*/////////////////////////////////////////////////////////////// Admin Roles //////////////////////////////////////////////////////////////*/ /// @notice has access to all admin functionality on pods bytes32 internal constant POD_ADMIN = keccak256("POD_ADMIN"); /// @notice capable of granting and revoking other TribeRoles from having veto power over a pod bytes32 internal constant POD_VETO_ADMIN = keccak256("POD_VETO_ADMIN"); /// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE. bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN"); /// @notice manages the Collateralization Oracle as well as other protocol oracles. bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE"); /// @notice manages TribalChief incentives and related functionality. bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE"); /// @notice admin of PCVGuardian bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE"); /// @notice admin of all Minor Roles bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN"); /// @notice admin of the Fuse protocol bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN"); /// @notice capable of vetoing DAO votes or optimistic timelocks bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN"); /// @notice capable of setting FEI Minters within global rate limits and caps bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN"); /// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN"); /// @notice manages meta-governance actions, like voting & delegating. /// Also used to vote for gauge weights & similar liquid governance things. bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN"); /// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking /// governance tokens from a pre-defined contract in order to eventually allow voting. /// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV. bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING"); /// @notice manages whitelisting of gauges where the protocol's tokens can be staked bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN"); /*/////////////////////////////////////////////////////////////// Minor Roles //////////////////////////////////////////////////////////////*/ bytes32 internal constant POD_METADATA_REGISTER_ROLE = keccak256("POD_METADATA_REGISTER_ROLE"); /// @notice capable of poking existing LBP auctions to exchange tokens. bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE"); /// @notice capable of engaging with Votium for voting incentives. bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE"); /// @notice capable of adding an address to multi rate limited bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE"); /// @notice capable of changing parameters within non-critical ranges bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE"); /// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE"); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPodAdminGateway { event AddPodMember(uint256 indexed podId, address member); event RemovePodMember(uint256 indexed podId, address member); event UpdatePodAdmin(uint256 indexed podId, address oldPodAdmin, address newPodAdmin); event PodMembershipTransferLock(uint256 indexed podId, bool lock); // Veto functionality event VetoTimelock(uint256 indexed podId, address indexed timelock, bytes32 proposalId); function getSpecificPodAdminRole(uint256 _podId) external pure returns (bytes32); function getSpecificPodGuardianRole(uint256 _podId) external pure returns (bytes32); function addPodMember(uint256 _podId, address _member) external; function batchAddPodMember(uint256 _podId, address[] calldata _members) external; function removePodMember(uint256 _podId, address _member) external; function batchRemovePodMember(uint256 _podId, address[] calldata _members) external; function lockMembershipTransfers(uint256 _podId) external; function unlockMembershipTransfers(uint256 _podId) external; function veto(uint256 _podId, bytes32 proposalId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; interface IPodFactory { /// @notice Configuration used when creating a pod /// @param members List of members to be added to the pod /// @param threshold Number of members that need to approve a transaction on the Gnosis safe /// @param label Metadata, Human readable label for the pod /// @param ensString Metadata, ENS name of the pod /// @param imageUrl Metadata, URL to a image to represent the pod in frontends /// @param minDelay Delay on the timelock struct PodConfig { address[] members; uint256 threshold; bytes32 label; string ensString; string imageUrl; address admin; uint256 minDelay; } event CreatePod(uint256 indexed podId, address indexed safeAddress, address indexed timelock); event CreateTimelock(address indexed timelock); event UpdatePodController(address indexed oldController, address indexed newController); event UpdateDefaultPodController(address indexed oldController, address indexed newController); function deployCouncilPod(PodConfig calldata _config) external returns ( uint256, address, address ); function defaultPodController() external view returns (ControllerV1); function getMemberToken() external view returns (MemberToken); function getPodSafeAddresses() external view returns (address[] memory); function getNumberOfPods() external view returns (uint256); function getPodController(uint256 podId) external view returns (ControllerV1); function getPodSafe(uint256 podId) external view returns (address); function getPodTimelock(uint256 podId) external view returns (address); function getNumMembers(uint256 podId) external view returns (uint256); function getPodMembers(uint256 podId) external view returns (address[] memory); function getPodThreshold(uint256 podId) external view returns (uint256); function getIsMembershipTransferLocked(uint256 podId) external view returns (bool); function getNextPodId() external view returns (uint256); function getPodAdmin(uint256 podId) external view returns (address); function createOptimisticPod(PodConfig calldata _config) external returns ( uint256, address, address ); function updateDefaultPodController(address _newDefaultController) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /** * @dev Hook that is called after any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 supply = _totalSupply[id]; require(supply >= amount, "ERC1155: burn amount exceeds totalSupply"); unchecked { _totalSupply[id] = supply - amount; } } } } } pragma solidity 0.8.7; interface IControllerRegistry{ /** * @param _controller Address to check if registered as a controller * @return Boolean representing if the address is a registered as a controller */ function isRegistered(address _controller) external view returns (bool); } pragma solidity 0.8.7; interface IControllerBase { /** * @param operator The account address that initiated the action * @param from The account address sending the membership token * @param to The account address recieving the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Arbitrary data */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity 0.8.7; import "./IControllerBase.sol"; interface IControllerV1 is IControllerBase { function updatePodEnsRegistrar(address _podEnsRegistrar) external; /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external; /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external; /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external; /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external; } pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface IMemberToken is IERC1155 { /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) external view returns (uint256); /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) external view returns (bool); function getNextAvailablePodId() external view returns (uint256); /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external; /** * @param _account The account address to transfer the membership token to * @param _id The membership token id to mint * @param data Arbitrary data */ function mint( address _account, uint256 _id, bytes memory data ) external; /** * @param _accounts The account addresses to transfer the membership tokens to * @param _id The membership token id to mint * @param data Arbitrary data */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) external; function createPod(address[] memory _accounts, bytes memory data) external returns (uint256); } pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IGnosisSafe.sol"; import "./interfaces/IGnosisSafeProxyFactory.sol"; import "@gnosis.pm/zodiac/contracts/guard/BaseGuard.sol"; contract SafeTeller is BaseGuard { using Address for address; // mainnet: 0x76E2cFc1F5Fa8F6a5b3fC4c8F4788F0116861F9B; address public immutable proxyFactoryAddress; // mainnet: 0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F; address public immutable gnosisMasterAddress; address public immutable fallbackHandlerAddress; string public constant FUNCTION_SIG_SETUP = "setup(address[],uint256,address,bytes,address,address,uint256,address)"; string public constant FUNCTION_SIG_EXEC = "execTransaction(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,bytes)"; string public constant FUNCTION_SIG_ENABLE = "delegateSetup(address)"; bytes4 public constant ENCODED_SIG_ENABLE_MOD = bytes4(keccak256("enableModule(address)")); bytes4 public constant ENCODED_SIG_DISABLE_MOD = bytes4(keccak256("disableModule(address,address)")); bytes4 public constant ENCODED_SIG_SET_GUARD = bytes4(keccak256("setGuard(address)")); address internal constant SENTINEL = address(0x1); // pods with admin have modules locked by default mapping(address => bool) public areModulesLocked; /** * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _proxyFactoryAddress, address _gnosisMasterAddress, address _fallbackHanderAddress ) { proxyFactoryAddress = _proxyFactoryAddress; gnosisMasterAddress = _gnosisMasterAddress; fallbackHandlerAddress = _fallbackHanderAddress; } /** * @param _safe The address of the safe * @param _newSafeTeller The address of the new safe teller contract */ function migrateSafeTeller( address _safe, address _newSafeTeller, address _prevModule ) internal { // add new safeTeller bytes memory enableData = abi.encodeWithSignature( "enableModule(address)", _newSafeTeller ); bool enableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, enableData, IGnosisSafe.Operation.Call ); require(enableSuccess, "Migration failed on enable"); // validate prevModule of current safe teller (address[] memory moduleBuffer, ) = IGnosisSafe(_safe) .getModulesPaginated(_prevModule, 1); require(moduleBuffer[0] == address(this), "incorrect prevModule"); // disable current safeTeller bytes memory disableData = abi.encodeWithSignature( "disableModule(address,address)", _prevModule, address(this) ); bool disableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, disableData, IGnosisSafe.Operation.Call ); require(disableSuccess, "Migration failed on disable"); } /** * @dev sets the safeteller as safe guard, called after migration * @param _safe The address of the safe */ function setSafeTellerAsGuard(address _safe) internal { bytes memory transferData = abi.encodeWithSignature( "setGuard(address)", address(this) ); bool guardSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, transferData, IGnosisSafe.Operation.Call ); require(guardSuccess, "Could not enable guard"); } function getSafeMembers(address safe) public view returns (address[] memory) { return IGnosisSafe(safe).getOwners(); } function isSafeModuleEnabled(address safe) public view returns (bool) { return IGnosisSafe(safe).isModuleEnabled(address(this)); } function isSafeMember(address safe, address member) public view returns (bool) { return IGnosisSafe(safe).isOwner(member); } /** * @param _owners The addresses to be owners of the safe * @param _threshold The number of owners that are required to sign a transaciton * @return safeAddress The address of the new safe */ function createSafe(address[] memory _owners, uint256 _threshold) internal returns (address safeAddress) { bytes memory data = abi.encodeWithSignature( FUNCTION_SIG_ENABLE, address(this) ); // encode the setup call that will be called on the new proxy safe // from the proxy factory bytes memory setupData = abi.encodeWithSignature( FUNCTION_SIG_SETUP, _owners, _threshold, this, data, fallbackHandlerAddress, address(0), uint256(0), address(0) ); try IGnosisSafeProxyFactory(proxyFactoryAddress).createProxy( gnosisMasterAddress, setupData ) returns (address newSafeAddress) { // add safe teller as guard setSafeTellerAsGuard(newSafeAddress); return newSafeAddress; } catch (bytes memory) { revert("Create Proxy With Data Failed"); } } /** * @param to The account address to add as an owner * @param safe The address of the safe */ function onMint(address to, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); bytes memory data = abi.encodeWithSignature( "addOwnerWithThreshold(address,uint256)", to, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address to be removed as an owner * @param safe The address of the safe */ function onBurn(address from, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom = address(0); for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } if (owners.length - 1 < threshold) threshold -= 1; bytes memory data = abi.encodeWithSignature( "removeOwner(address,address,uint256)", prevFrom, from, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address being removed as an owner * @param to The address being added as an owner * @param safe The address of the safe */ function onTransfer( address from, address to, address safe ) internal { address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom; for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } bytes memory data = abi.encodeWithSignature( "swapOwner(address,address,address)", prevFrom, from, to ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will execute a tx from the safe that will update the safe's ENS in the reverse resolver * @param safe safe address * @param reverseRegistrar The ENS default reverseRegistar * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function setupSafeReverseResolver( address safe, address reverseRegistrar, string memory _ensString ) internal { bytes memory data = abi.encodeWithSignature( "setName(string)", _ensString ); bool success = IGnosisSafe(safe).execTransactionFromModule( reverseRegistrar, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will be called by the safe at tx time and prevent module disable on pods with admins * @param safe safe address * @param isLocked safe address */ function setModuleLock(address safe, bool isLocked) internal { areModulesLocked[safe] = isLocked; } /** * @dev This will be called by the safe at execution time time * @param to Destination address of Safe transaction. * @param value Ether value of Safe transaction. * @param data Data payload of Safe transaction. * @param operation Operation type of Safe transaction. * @param safeTxGas Gas that should be used for the Safe transaction. * @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) * @param gasPrice Gas price that should be used for the payment calculation. * @param gasToken Token address (or 0 if ETH) that is used for the payment. * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). * @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) * @param msgSender Account executing safe transaction */ function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external view override { address safe = msg.sender; // if safe isn't locked return if (!areModulesLocked[safe]) return; if (data.length >= 4) { require( bytes4(data) != ENCODED_SIG_ENABLE_MOD, "Cannot Enable Modules" ); require( bytes4(data) != ENCODED_SIG_DISABLE_MOD, "Cannot Disable Modules" ); require( bytes4(data) != ENCODED_SIG_SET_GUARD, "Cannot Change Guard" ); } } function checkAfterExecution(bytes32, bool) external view override {} // TODO: move to library // Used in a delegate call to enable module add on setup function enableModule(address module) external { require(module == address(0)); } function delegateSetup(address _context) external { this.enableModule(_context); } } pragma solidity 0.8.7; interface IPodEnsRegistrar { function getRootNode() external view returns (bytes32); function registerPod( bytes32 label, address podSafe, address podCreator ) external returns (address); function register(bytes32 label, address owner) external; function setText( bytes32 node, string calldata key, string calldata value ) external; function addressToNode(address input) external returns (bytes32); function getEnsNode(bytes32 label) external view returns (bytes32); } pragma solidity 0.8.7; interface IGnosisSafe { enum Operation {Call, DelegateCall} /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes calldata data, Operation operation ) external returns (bool success); /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() external view returns (address[] memory); function isOwner(address owner) external view returns (bool); function getThreshold() external returns (uint256); /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next); /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) external view returns (bool); /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external; } pragma solidity 0.8.7; interface IGnosisSafeProxyFactory { /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) external returns (address); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../interfaces/IGuard.sol"; abstract contract BaseGuard is IERC165 { function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } /// @dev Module transactions only use the first four parameters: to, value, data, and operation. /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. /// @notice This interface is used to maintain compatibilty with Gnosis Safe transaction guards. function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external virtual; function checkAfterExecution(bytes32 txHash, bool success) external virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IGuard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting(address indexed _to, address indexed _minter, uint256 _amount); event Burning(address indexed _to, address indexed _burner, uint256 _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = _setInitializedVersion(1); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { bool isTopLevelCall = _setInitializedVersion(version); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(version); } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); } function _setInitializedVersion(uint8 version) private returns (bool) { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level // of initializers, because in other contexts the contract may have been reentered. if (_initializing) { require( version == 1 && !Address.isContract(address(this)), "Initializable: contract is already initialized" ); return false; } else { require(_initialized < version, "Initializable: contract is already initialized"); _initialized = version; return true; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "./IPermissions.sol"; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControlEnumerable { bytes32 public constant override BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant override MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant override PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant override GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant override GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() { // Appointed as a governor so guardian can have indirect access to revoke ability _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require(isGovernor(msg.sender), "Permissions: Caller is not a governor"); _; } modifier onlyGuardian() { require(isGuardian(msg.sender), "Permissions: Caller is not a guardian"); _; } /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external override onlyGuardian { require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor"); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian function isGuardian(address _address) public view override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./IIncentive.sol"; import "../refs/CoreRef.sol"; /// @title FEI stablecoin /// @author Fei Protocol contract Fei is IFei, ERC20Burnable, CoreRef { /// @notice get associated incentive contract, 0 address if N/A mapping(address => address) public override incentiveContract; // solhint-disable-next-line var-name-mixedcase bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) ERC20("Fei USD", "FEI") CoreRef(core) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), chainId, address(this) ) ); } /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint256 amount) external override onlyMinter whenNotPaused { _mint(account, amount); emit Minting(account, msg.sender, amount); } /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint256 amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint256 amount) public override(IFei, ERC20Burnable) onlyBurner whenNotPaused { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); _checkAndApplyIncentives(sender, recipient, amount); } function _checkAndApplyIncentives( address sender, address recipient, uint256 amount ) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) { IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount); } // all incentive, if active applies to every transfer address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount); } } /// @notice permit spending of FEI /// @param owner the FEI holder /// @param spender the approved operator /// @param value the amount approved /// @param deadline the deadline after which the approval is no longer valid function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "Fei: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "Fei: INVALID_SIGNATURE"); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint256 public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint256 rawAmount) external { require(msg.sender == minter, "Tribe: only the minter can mint"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(signatory == owner, "Tribe: unauthorized"); require(block.timestamp <= deadline, "Tribe: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); require(block.timestamp <= expiry, "Tribe: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Tribe: cannot transfer from the zero address"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Tribe: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint256) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
Allows admin to unlock the safe modules and allow them to be edited by members _podId The id number of the pod _isLocked true - pod modules cannot be added/removed/
function setPodModuleLock(uint256 _podId, bool _isLocked) external override { require( msg.sender == podAdmin[_podId], "Must be admin to set module lock" ); setModuleLock(podIdToSafe[_podId], _isLocked); }
9,855,944
pragma solidity ^0.4.18; /** SafeMath libs are inspired by: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol * There is debate as to whether this lib should use assert or require: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/565 * `require` is used in these libraries for the following reasons: * - overflows should not be checked in contract function bodies; DRY * - "valid" user input can cause overflows, which should not assert() */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } library SafeMath64 { function sub(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a); return a - b; } function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; require(c >= a); return c; } } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // https://github.com/ethereum/EIPs/issues/179 contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // https://github.com/ethereum/EIPs/issues/20 contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/DetailedERC20.sol contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** KarmaToken has the following properties: * * User Creation: * - Self-registration * - Owner signs hash(address, username, endowment), and sends to user * - User registers with username, endowment, and signature to create new account. * - Mod creates new user. * - Users are first eligible to withdraw dividends for the period after account creation. * * Karma/Token Rules: * - Karma is created by initial user creation endowment. * - Karma can also be minted by mod into an existing account. * - Karma can only be transferred to existing account holder. * - Karma implements the ERC20 token interface. * * Dividends: * - each user can withdraw a dividend once per month. * - dividend is total contract value minus owner cut at end of the month, divided by total number of users at end of month. * - owner cut is determined at beginning of new period. * - user has 1 month to withdraw their dividend from the previous month. * - if user does not withdraw their dividend, their share will be given to owner. * - mod can place a user on a 1 month "timeout", whereby they won't be eligible for a dividend. * Eg: 10 eth is sent to the contract in January, owner cut is 30%. * There are 70 token holders on Jan 31. At any time in February, each token holder can withdraw .1 eth for their January * dividend (unless they were given a "timeout" in January). */ contract Karma is Ownable, DetailedERC20("KarmaToken", "KARMA", 0) { // SafeMath libs are responsible for checking overflow. using SafeMath for uint256; using SafeMath64 for uint64; struct User { bytes20 username; uint64 karma; uint16 canWithdrawPeriod; uint16 birthPeriod; } // Manage users. mapping(address => User) public users; mapping(bytes20 => address) public usernames; // Manage dividend payments. uint256 public epoch; // Timestamp at start of new period. uint256 dividendPool; // Total amount of dividends to pay out for last period. uint256 public dividend; // Per-user share of last period's dividend. uint256 public ownerCut; // Percentage, in basis points, of owner cut of this period's payments. uint64 public numUsers; // Number of users created before this period. uint64 public newUsers; // Number of users created during this period. uint16 public currentPeriod = 1; address public moderator; mapping(address => mapping (address => uint256)) internal allowed; event Mint(address indexed to, uint256 amount); event PeriodEnd(uint16 period, uint256 amount, uint64 users); event Payment(address indexed from, uint256 amount); event Withdrawal(address indexed to, uint16 indexed period, uint256 amount); event NewUser(address addr, bytes20 username, uint64 endowment); modifier onlyMod() { require(msg.sender == moderator); _; } function Karma(uint256 _startEpoch) public { epoch = _startEpoch; moderator = msg.sender; } function() payable public { Payment(msg.sender, msg.value); } /** * Owner Functions */ function setMod(address _newMod) public onlyOwner { moderator = _newMod; } // Owner should call this on 1st of every month. // _ownerCut is new owner cut for new period. function newPeriod(uint256 _ownerCut) public onlyOwner { require(now >= epoch + 28 days); require(_ownerCut <= 10000); uint256 unclaimedDividend = dividendPool; uint256 ownerRake = (this.balance-unclaimedDividend) * ownerCut / 10000; dividendPool = this.balance - unclaimedDividend - ownerRake; // Calculate dividend. uint64 existingUsers = numUsers; if (existingUsers == 0) { dividend = 0; } else { dividend = dividendPool / existingUsers; } numUsers = numUsers.add(newUsers); newUsers = 0; currentPeriod++; epoch = now; ownerCut = _ownerCut; msg.sender.transfer(ownerRake + unclaimedDividend); PeriodEnd(currentPeriod-1, this.balance, existingUsers); } /** * Mod Functions */ function createUser(address _addr, bytes20 _username, uint64 _amount) public onlyMod { newUser(_addr, _username, _amount); } // Send karma to existing account. function mint(address _addr, uint64 _amount) public onlyMod { require(users[_addr].canWithdrawPeriod != 0); users[_addr].karma = users[_addr].karma.add(_amount); totalSupply = totalSupply.add(_amount); Mint(_addr, _amount); } // If a user has been bad, they won't be able to receive a dividend :( function timeout(address _addr) public onlyMod { require(users[_addr].canWithdrawPeriod != 0); users[_addr].canWithdrawPeriod = currentPeriod + 1; } /** * User Functions */ // Owner will sign hash(address, username, amount), and address owner uses this // signature to register their account. function register(bytes20 _username, uint64 _endowment, bytes _sig) public { require(recover(keccak256(msg.sender, _username, _endowment), _sig) == owner); newUser(msg.sender, _username, _endowment); } // User can withdraw their share of donations from the previous month. function withdraw() public { require(users[msg.sender].canWithdrawPeriod != 0); require(users[msg.sender].canWithdrawPeriod < currentPeriod); users[msg.sender].canWithdrawPeriod = currentPeriod; dividendPool -= dividend; msg.sender.transfer(dividend); Withdrawal(msg.sender, currentPeriod-1, dividend); } /** * ERC20 Functions */ function balanceOf(address _owner) public view returns (uint256 balance) { return users[_owner].karma; } // Contrary to most ERC20 implementations, require that recipient is existing user. function transfer(address _to, uint256 _value) public returns (bool) { require(users[_to].canWithdrawPeriod != 0); require(_value <= users[msg.sender].karma); // Type assertion to uint64 is safe because we require that _value is < uint64 above. users[msg.sender].karma = users[msg.sender].karma.sub(uint64(_value)); users[_to].karma = users[_to].karma.add(uint64(_value)); Transfer(msg.sender, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // Contrary to most ERC20 implementations, require that recipient is existing user. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(users[_to].canWithdrawPeriod != 0); require(_value <= users[_from].karma); require(_value <= allowed[_from][msg.sender]); users[_from].karma = users[_from].karma.sub(uint64(_value)); users[_to].karma = users[_to].karma.add(uint64(_value)); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * Private Functions */ // Ensures that username isn't taken, and account doesn't already exist for // user's address. function newUser(address _addr, bytes20 _username, uint64 _endowment) private { require(usernames[_username] == address(0)); require(users[_addr].canWithdrawPeriod == 0); users[_addr].canWithdrawPeriod = currentPeriod + 1; users[_addr].birthPeriod = currentPeriod; users[_addr].karma = _endowment; users[_addr].username = _username; usernames[_username] = _addr; newUsers = newUsers.add(1); totalSupply = totalSupply.add(_endowment); NewUser(_addr, _username, _endowment); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ECRecovery.sol function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } }
Owner should call this on 1st of every month. _ownerCut is new owner cut for new period. Calculate dividend.
function newPeriod(uint256 _ownerCut) public onlyOwner { require(now >= epoch + 28 days); require(_ownerCut <= 10000); uint256 unclaimedDividend = dividendPool; uint256 ownerRake = (this.balance-unclaimedDividend) * ownerCut / 10000; dividendPool = this.balance - unclaimedDividend - ownerRake; uint64 existingUsers = numUsers; if (existingUsers == 0) { dividend = 0; dividend = dividendPool / existingUsers; } numUsers = numUsers.add(newUsers); newUsers = 0; currentPeriod++; epoch = now; ownerCut = _ownerCut; msg.sender.transfer(ownerRake + unclaimedDividend); PeriodEnd(currentPeriod-1, this.balance, existingUsers); }
6,895,790
./full_match/137/0xab03C0c0Ba39a886eD51757272E91cd739542118/sources/contracts/KeeperRewardDistributor/KeeperRewardDistributor.sol
@inheritdoc IKeeperRewardDistributor/
function claim( uint256 _pmxAmount, uint256 _nativeAmount ) external override nonReentrant whenNotPaused notBlackListed { KeeperBalance memory balance = keeperBalance[msg.sender]; if (_pmxAmount > balance.pmxBalance) _pmxAmount = balance.pmxBalance; if (_nativeAmount > balance.nativeBalance) _nativeAmount = balance.nativeBalance; if (_pmxAmount > 0) { keeperBalance[msg.sender].pmxBalance -= _pmxAmount; totalBalance.pmxBalance -= _pmxAmount; ITreasury(treasury).transferFromTreasury(_pmxAmount, pmx, msg.sender); emit ClaimFees(msg.sender, pmx, _pmxAmount); } if (_nativeAmount > 0) { keeperBalance[msg.sender].nativeBalance -= _nativeAmount; totalBalance.nativeBalance -= _nativeAmount; ITreasury(treasury).transferFromTreasury(_nativeAmount, NATIVE_CURRENCY, msg.sender); emit ClaimFees(msg.sender, NATIVE_CURRENCY, _nativeAmount); } }
4,727,309
pragma solidity ^0.4.18; import '../core/RequestCore.sol'; import '../base/math/SafeMathUint8.sol'; import './RequestEthereumCollect.sol'; import '../base/token/ERC20.sol'; /** * @title RequestEthereum * * @dev RequestEthereum is the currency contract managing the request in Ethereum * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer() */ contract RequestEthereum is RequestEthereumCollect { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // RequestCore object RequestCore public requestCore; // payment addresses by requestId (optional). We separate the Identity of the payee/payer (in the core) and the wallet address in the currency contract mapping(bytes32 => address[256]) public payeesPaymentAddress; mapping(bytes32 => address) public payerRefundAddress; /* * @dev Constructor * @param _requestCoreAddress Request Core address * @param _requestBurnerAddress Request Burner contract address */ function RequestEthereum(address _requestCoreAddress, address _requestBurnerAddress) RequestEthereumCollect(_requestBurnerAddress) public { requestCore=RequestCore(_requestCoreAddress); } /* * @dev Function to create a request as payee * * @dev msg.sender will be the payee * @dev if _payeesPaymentAddress.length > _payeesIdAddress.length, the extra addresses will be stored but never used * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payer Entity expected to pay * @param _payerRefundAddress Address of refund for the payer (optional) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayee( address[] _payeesIdAddress, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payer, address _payerRefundAddress, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0); uint256 fees; (requestId, fees) = createRequest(_payer, _payeesIdAddress, _payeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data); // check if the value send match exactly the fees (no under or over payment allowed) require(fees == msg.value); return requestId; } /* * @dev Function to create a request as payer. The request is payed if _payeeAmounts > 0. * * @dev msg.sender will be the payer * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee the others are subPayees) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payerRefundAddress Address of refund for the payer (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayer( address[] _payeesIdAddress, int256[] _expectedAmounts, address _payerRefundAddress, uint256[] _payeeAmounts, uint256[] _additionals, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender != _payeesIdAddress[0] && _payeesIdAddress[0] != 0); // payeesPaymentAddress is not offered as argument here to avoid scam address[] memory emptyPayeesPaymentAddress = new address[](0); uint256 fees; (requestId, fees) = createRequest(msg.sender, _payeesIdAddress, emptyPayeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data); // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees)); return requestId; } /* * @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also) * * @dev _payer will be set msg.sender * @dev if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _requestData nested bytes containing : creator, payer, payees, expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature in bytes * * @return Returns the id of the request */ function broadcastSignedRequestAsPayer( bytes _requestData, // gather data to avoid "stack too deep" address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _expirationDate, bytes _signature) external payable whenNotPaused returns(bytes32) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature)); // create accept and pay the request return createAcceptAndPayFromBytes(_requestData, _payeesPaymentAddress, _payeeAmounts, _additionals); } /* * @dev Internal function to create, accept, add additionals and pay a request as Payer * * @dev msg.sender must be _payer * * @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * * @return Returns the id of the request */ function createAcceptAndPayFromBytes( bytes _requestData, address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals) internal returns(bytes32 requestId) { // extract main payee address mainPayee = extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0); // creator must be the main payee require(extractAddress(_requestData, 0) == mainPayee); // extract the number of payees uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) { // extract the expectedAmount for the payee[i] // NB: no need of SafeMath here because 0 < i < 256 (uint8) int256 expectedAmountTemp = int256(extractBytes32(_requestData, 61 + 52 * uint256(i))); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); // all expected amount must be positibe require(expectedAmountTemp>0); } // collect the fees uint256 fees = collectEstimation(totalExpectedAmounts); // check fees has been well received // do the action and assertion in one to save a variable require(collectForREQBurning(fees)); // insert the msg.sender as the payer in the bytes updateBytes20inBytes(_requestData, 20, bytes20(msg.sender)); // store request in the core, requestId = requestCore.createRequestFromBytes(_requestData); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees)); return requestId; } /* * @dev Internal function to create a request * * @dev msg.sender is the creator of the request * * @param _payer Payer identity address * @param _payees Payees identity address * @param _payeesPaymentAddress Payees payment address * @param _expectedAmounts Expected amounts to be received by payees * @param _payerRefundAddress payer refund address * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequest( address _payer, address[] _payees, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payerRefundAddress, string _data) internal returns(bytes32 requestId, uint256 fees) { int256 totalExpectedAmounts = 0; for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1)) { // all expected amount must be positive require(_expectedAmounts[i]>=0); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]); } // collect the fees fees = collectEstimation(totalExpectedAmounts); // check fees has been well received require(collectForREQBurning(fees)); // store request in the core requestId= requestCore.createRequest(msg.sender, _payees, _expectedAmounts, _payer, _data); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // set payment address for payer if(_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } } /* * @dev Internal function to accept, add additionals and pay a request as Payer * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to _amountPaid) * @param _additionals Will increase the ExpectedAmounts of payees * @param _amountPaid amount in msg.value minus the fees * */ function acceptAndPay( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _amountPaid) internal { requestCore.accept(_requestId); additionalInternal(_requestId, _additionals); if(_amountPaid > 0) { paymentInternal(_requestId, _payeeAmounts, _amountPaid); } } // ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function to accept a request * * @dev msg.sender must be _payer * @dev A request can also be accepted by using directly the payment function on a request in the Created status * * @param _requestId id of the request */ function accept(bytes32 _requestId) external whenNotPaused condition(requestCore.getPayer(_requestId)==msg.sender) condition(requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } /* * @dev Function to cancel a request * * @dev msg.sender must be the _payer or the _payee. * @dev only request with balance equals to zero can be cancel * * @param _requestId id of the request */ function cancel(bytes32 _requestId) external whenNotPaused { // payer can cancel if request is just created bool isPayerAndCreated = requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created; // payee can cancel when request is not canceled yet bool isPayeeAndNotCanceled = requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled; require(isPayerAndCreated || isPayeeAndNotCanceled); // impossible to cancel a Request with any payees balance != 0 require(requestCore.areAllBalanceNull(_requestId)); requestCore.cancel(_requestId); } // ---------------------------------------------------------------------------------------- // ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function PAYABLE to pay a request in ether. * * @dev the request will be automatically accepted if msg.sender==payer. * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equal to msg.value) in wei * @param _additionalsAmount amount of additionals per payee in wei to declare */ function paymentAction( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionalAmounts) external whenNotPaused payable condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) condition(_additionalAmounts.length == 0 || msg.sender == requestCore.getPayer(_requestId)) { // automatically accept request if request is created and msg.sender is payer if(requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) { requestCore.accept(_requestId); } additionalInternal(_requestId, _additionalAmounts); paymentInternal(_requestId, _payeeAmounts, msg.value); } /* * @dev Function PAYABLE to pay back in ether a request to the payer * * @dev msg.sender must be one of the payees * @dev the request must be created or accepted * * @param _requestId id of the request */ function refundAction(bytes32 _requestId) external whenNotPaused payable { refundInternal(_requestId, msg.sender, msg.value); } /* * @dev Function to declare a subtract * * @dev msg.sender must be _payee * @dev the request must be accepted or created * * @param _requestId id of the request * @param _subtractAmounts amounts of subtract in wei to declare (index 0 is for main payee) */ function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts) external whenNotPaused condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) onlyRequestPayee(_requestId) { for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) { if(_subtractAmounts[i] != 0) { // subtract must be equal or lower than amount expected require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe()); // store and declare the subtract in the core requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe()); } } } /* * @dev Function to declare an additional * * @dev msg.sender must be _payer * @dev the request must be accepted or created * * @param _requestId id of the request * @param _additionalAmounts amounts of additional in wei to declare (index 0 is for main payee) */ function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts) external whenNotPaused condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) onlyRequestPayer(_requestId) { additionalInternal(_requestId, _additionalAmounts); } // ---------------------------------------------------------------------------------------- // ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function internal to manage additional declaration * * @param _requestId id of the request * @param _additionalAmounts amount of additional to declare */ function additionalInternal(bytes32 _requestId, uint256[] _additionalAmounts) internal { // we cannot have more additional amounts declared than actual payees but we can have fewer require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) { if(_additionalAmounts[i] != 0) { // Store and declare the additional in the core requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe()); } } } /* * @dev Function internal to manage payment declaration * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to msg.value) * @param _value amount paid */ function paymentInternal( bytes32 _requestId, uint256[] _payeeAmounts, uint256 _value) internal { // we cannot have more amounts declared than actual payees require(_payeeAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); uint256 totalPayeeAmounts = 0; for(uint8 i = 0; i < _payeeAmounts.length; i = i.add(1)) { if(_payeeAmounts[i] != 0) { // compute the total amount declared totalPayeeAmounts = totalPayeeAmounts.add(_payeeAmounts[i]); // Store and declare the payment to the core requestCore.updateBalance(_requestId, i, _payeeAmounts[i].toInt256Safe()); // pay the payment address if given, the id address otherwise address addressToPay; if(payeesPaymentAddress[_requestId][i] == 0) { addressToPay = requestCore.getPayeeAddress(_requestId, i); } else { addressToPay = payeesPaymentAddress[_requestId][i]; } //payment done, the money was sent fundOrderInternal(addressToPay, _payeeAmounts[i]); } } // check if payment repartition match the value paid require(_value==totalPayeeAmounts); } /* * @dev Function internal to manage refund declaration * * @param _requestId id of the request * @param _fromAddress address from where the refund has been done * @param _amount amount of the refund in wei to declare */ function refundInternal( bytes32 _requestId, address _fromAddress, uint256 _amount) condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) internal { // Check if the _fromAddress is a payeesId // int16 to allow -1 value int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _fromAddress); if(payeeIndex < 0) { uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1); // if not ID addresses maybe in the payee payments addresses for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) { if(payeesPaymentAddress[_requestId][i] == _fromAddress) { // get the payeeIndex payeeIndex = int16(i); } } } // the address must be found somewhere require(payeeIndex >= 0); // Casting to uin8 doesn't lose bits because payeeIndex < 256. payeeIndex was declared int16 to allow -1 requestCore.updateBalance(_requestId, uint8(payeeIndex), -_amount.toInt256Safe()); // refund to the payment address if given, the id address otherwise address addressToPay = payerRefundAddress[_requestId]; if(addressToPay == 0) { addressToPay = requestCore.getPayer(_requestId); } // refund declared, the money is ready to be sent to the payer fundOrderInternal(addressToPay, _amount); } /* * @dev Function internal to manage fund mouvement * @dev We had to chose between a withdrawal pattern, a transfer pattern or a transfer+withdrawal pattern and chose the transfer pattern. * @dev The withdrawal pattern would make UX difficult. The transfer+withdrawal pattern would make contracts interacting with the request protocol complex. * @dev N.B.: The transfer pattern will have to be clearly explained to users. It enables a payee to create unpayable requests. * * @param _recipient address where the wei has to be sent to * @param _amount amount in wei to send * */ function fundOrderInternal( address _recipient, uint256 _amount) internal { _recipient.transfer(_amount); } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _data bytes containing all the data packed * @param _payeesPaymentAddress array of payees payment addresses * @param _expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate) */ function getRequestHash( // _requestData is from the core bytes _requestData, // _payeesPaymentAddress and _expirationDate are not from the core but needs to be signed address[] _payeesPaymentAddress, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this, _requestData, _payeesPaymentAddress, _expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* * @dev Check the validity of a signed request & the expiration date * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkRequestSignature( bytes _requestData, address[] _payeesPaymentAddress, uint256 _expirationDate, bytes _signature) public view returns (bool) { bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(_signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = extractBytes32(_signature, 0); bytes32 s = extractBytes32(_signature, 32); // check signature of the hash with the creator address return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s); } //modifier modifier condition(bool c) { require(c); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is the main payee * @dev Revert if msg.sender is not the main payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender); _; } /* * @dev modify 20 bytes in a bytes * @param data bytes to modify * @param offset position of the first byte to modify * @param b bytes20 to insert * @return address */ function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >=0 && offset + 20 <= data.length); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } } /* * @dev extract an address in a bytes * @param data bytes from where the address will be extract * @param offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /** * @dev transfer to owner any tokens send by mistake on this contracts * @param token The address of the token to transfer. * @param amount The amount to be transfered. */ function emergencyERC20Drain(ERC20 token, uint amount ) public onlyOwner { token.transfer(owner, amount); } }
---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------ Function PAYABLE to pay a request in ether. the request will be automatically accepted if msg.sender==payer. _requestId id of the request _payeesAmounts Amount to pay to payees (sum must be equal to msg.value) in wei _additionalsAmount amount of additionals per payee in wei to declare/ automatically accept request if request is created and msg.sender is payer
function paymentAction( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionalAmounts) external whenNotPaused payable condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) condition(_additionalAmounts.length == 0 || msg.sender == requestCore.getPayer(_requestId)) { if(requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) { requestCore.accept(_requestId); } additionalInternal(_requestId, _additionalAmounts); paymentInternal(_requestId, _payeeAmounts, msg.value); }
14,089,340
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol"; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CertChain ERC721 token standard implementation * @author rjkz808 */ contract CertToken is ERC721 { using AddressUtils for address; using SafeMath for uint256; string internal constant name_ = "CertChain"; string internal constant symbol_ = "CRT"; uint8 internal constant decimals_ = 0; bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; uint256[] internal allTokens; mapping (uint256 => address) internal tokenOwner; mapping (uint256 => address) internal tokenApproval; mapping (address => mapping (address => bool)) internal operatorApproval; mapping (address => uint256[]) internal ownedTokens; mapping (uint256 => uint256) internal ownedTokensIndex; mapping (uint256 => uint256) internal allTokensIndex; mapping (uint256 => string) internal tokenURIs; mapping (bytes4 => bool) internal supportedInterfaces; event Burn(address indexed owner, uint256 tokenId); /** * @dev Reverts, if the `msg.sender` doesn't own the specified token * @param _tokenId uint256 ID of the token */ modifier onlyOwnerOf(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId)); _; } /** * @dev Constructor to register the implemented interfaces IDs */ constructor() public { _registerInterface(InterfaceId_ERC165); _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token short code * @return string the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Gets the token decimals * @notice This function is needed to keep the balance * @notice displayed in the MetaMask * @return uint8 the token decimals (0) */ function decimals() external pure returns (uint8) { return decimals_; } /** * @dev Gets the total issued tokens amount * @return uint256 the total tokens supply */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the balance of an account * @param _owner address the tokens holder * @return uint256 the account owned tokens amount */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } /** * @dev Gets the specified token owner * @param _tokenId uint256 ID of the token * @return address the token owner */ function ownerOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenOwner[_tokenId]; } /** * @dev Gets the token existence state * @param _tokenId uint256 ID of the token * @return bool the token existence state */ function exists(uint256 _tokenId) public view returns (bool) { return tokenOwner[_tokenId] != address(0); } /** * @dev Gets the token approval * @param _tokenId uint256 ID of the token * @return address the token spender */ function getApproved(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenApproval[_tokenId]; } /** * @dev Gets the operator approval state * @param _owner address the tokens holder * @param _operator address the tokens spender * @return bool the operator approval state */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return operatorApproval[_owner][_operator]; } /** * @dev Gets the specified address token ownership/spending state * @param _spender address the token spender * @param _tokenId uint256 the spending token ID * @return bool the ownership/spending state */ function isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) { require(_spender != address(0)); require(exists(_tokenId)); return( _spender == ownerOf(_tokenId) || _spender == getApproved(_tokenId) || isApprovedForAll(ownerOf(_tokenId), _spender) ); } /** * @dev Gets the token ID by the ownedTokens list index * @param _owner address the token owner * @param _index uint256 the token index * @return uint256 the token ID */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_owner != address(0)); require(_index < ownedTokens[_owner].length); return ownedTokens[_owner][_index]; } /** * @dev Gets the token ID by the allTokens list index * @param _index uint256 the token index * @return uint256 the token ID */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < allTokens.length); return allTokens[_index]; } /** * @dev Gets the token URI * @param _tokenId uint256 ID of the token * @return string the token URI */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the interface support state * @param _interfaceId bytes4 ID of the interface * @return bool the specified interface support state */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { require(_interfaceId != 0xffffffff); return supportedInterfaces[_interfaceId]; } /** * @dev Function to approve token to spend it * @param _to address the token spender * @param _tokenId ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(msg.sender == ownerOf(_tokenId)); require(_to != address(0)); tokenApproval[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Function to set the operator approval for the all owned tokens * @param _operator address the tokens spender * @param _approved bool the tokens approval state */ function setApprovalForAll(address _operator, bool _approved) public { require(_operator != address(0)); operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Function to clear an approval of the owned token * @param _tokenId uint256 ID of the token */ function clearApproval(uint256 _tokenId) public onlyOwnerOf(_tokenId) { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) { tokenApproval[_tokenId] = address(0); emit Approval(msg.sender, address(0), _tokenId); } } /** * @dev Function to send the owned/approved token * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_to != address(0)); _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); _addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract and with the additional transaction metadata * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); require(_onERC721Received(msg.sender, _from, _to, _tokenId, _data)); } /** * @dev Function to burn the owned token * @param _tokenId uint256 ID of the token to be burned */ function burn(uint256 _tokenId) public onlyOwnerOf(_tokenId) { _burn(msg.sender, _tokenId); } /** * @dev Function to burn the owned/approved token * @param _from address the token owner * @param _tokenId uint256 ID of the token to be burned */ function burnFrom(address _from, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); _burn(_from, _tokenId); } /** * @dev Internal function to clear an approval of the token * @param _tokenId uint256 ID of the token */ function _clearApproval(uint256 _tokenId) internal { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) tokenApproval[_tokenId] = address(0); } /** * @dev Internal function to add the token to the account * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be added */ function _addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); require(_to != address(0)); tokenOwner[_tokenId] = _to; ownedTokensIndex[_tokenId] = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); } /** * @dev Internal function to remove the token from its owner address * @param _from address the token owner * @param _tokenId uint256 ID of the token */ function _removeTokenFrom(address _from, uint256 _tokenId) internal { require(_from == ownerOf(_tokenId)); uint256 lastToken = ownedTokens[_from][ownedTokens[_from].length.sub(1)]; ownedTokens[_from][ownedTokensIndex[_tokenId]] = lastToken; ownedTokens[_from][ownedTokensIndex[lastToken]] = 0; ownedTokens[_from].length = ownedTokens[_from].length.sub(1); ownedTokensIndex[lastToken] = ownedTokensIndex[_tokenId]; ownedTokensIndex[_tokenId] = 0; tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to call the `onERC721Received` function if the * @dev token recepient is the smart contract * @param _operator address the `transfer` function caller * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function _onERC721Received( address _operator, address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (_to.isContract()) { ERC721Receiver receiver = ERC721Receiver(_to); return ERC721_RECEIVED == receiver.onERC721Received( _operator, _from, _tokenId, _data ); } return true; } /** * @dev Internal function the token * @param _owner address the token owner * @param _tokenId ID of the token to be burned */ function _burn(address _owner, uint256 _tokenId) internal { if (bytes(tokenURIs[_tokenId]).length > 0) delete tokenURIs[_tokenId]; _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); uint256 lastToken = allTokens[allTokens.length.sub(1)]; allTokens[allTokensIndex[_tokenId]] = lastToken; allTokens[allTokensIndex[lastToken]] = 0; allTokens.length = allTokens.length.sub(1); allTokensIndex[lastToken] = allTokensIndex[_tokenId]; allTokensIndex[_tokenId] = 0; emit Transfer(_owner, address(0), _tokenId); emit Burn(_owner, _tokenId); } /** * @dev Internal function to issue new token * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be issued * @param _uri string the new token URI */ function _mint(address _to, uint256 _tokenId, string _uri) internal { require(_to != address(0)); _addTokenTo(_to, _tokenId); _setTokenURI(_tokenId, _uri); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to set the token URI * @param _tokenId ID of the token * @param _uri string the token URI */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to register the implemented interface * @param _interfaceId bytes4 ID of the interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } }
Gets the token ID by the ownedTokens list index _owner address the token owner _index uint256 the token index return uint256 the token ID/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_owner != address(0)); require(_index < ownedTokens[_owner].length); return ownedTokens[_owner][_index]; }
6,435,008
/** * Copyright BOOSTRY Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity ^0.8.0; import "../access/Ownable.sol"; /// @title Escrowコントラクトのステートを永続化するためのEternalStorage /// @dev Storageのアクセスは認可したEscrowコントラクトに限定する contract EscrowStorage is Ownable { constructor() {} // ------------------------------------------------------------------- // 最新バージョンのEscrowコントラクトアドレス:LatestVersion // ------------------------------------------------------------------- /// 最新バージョンのEscrowコントラクトアドレス address public latestVersion; /// @notice Escrowコントラクトのバージョン更新 /// @dev コントラクトオーナーのみ実行が可能 /// @param _newVersion 新しいEscrowコントラクトのアドレス function upgradeVersion(address _newVersion) public onlyOwner() { latestVersion = _newVersion; } /// @dev 実行者が最新バージョンのEscrowアドレスであることをチェック modifier onlyLatestVersion() { require(msg.sender == latestVersion); _; } // ------------------------------------------------------------------- // 残高:Balance // ------------------------------------------------------------------- /// 残高情報 /// account => token => amount mapping(address => mapping(address => uint256)) private balances; /// @notice 残高の更新 /// @dev 最新バージョンのEscrowコントラクトのみ実行が可能 /// @param _account アドレス /// @param _token トークンアドレス /// @param _value 更新後の残高数量 /// @return 処理結果 function setBalance(address _account, address _token, uint256 _value) public onlyLatestVersion() returns (bool) { balances[_account][_token] = _value; return true; } /// @notice 残高数量の参照 /// @param _account アドレス /// @param _token トークンアドレス /// @return 残高数量 function getBalance(address _account, address _token) public view returns (uint256) { return balances[_account][_token]; } // ------------------------------------------------------------------- // 拘束数量:Commitment // ------------------------------------------------------------------- /// 拘束数量 /// account => token => amount mapping(address => mapping(address => uint256)) public commitments; /// @notice 拘束数量の更新 /// @dev 最新バージョンのEscrowコントラクトのみ実行が可能 /// @param _account アドレス /// @param _token トークンアドレス /// @param _value 更新後の数量 /// @return 処理結果 function setCommitment(address _account, address _token, uint256 _value) public onlyLatestVersion() returns (bool) { commitments[_account][_token] = _value; return true; } /// @notice 拘束数量の参照 /// @param _account アドレス /// @param _token トークンアドレス /// @return 拘束数量 function getCommitment(address _account, address _token) public view returns (uint256) { return commitments[_account][_token]; } // ------------------------------------------------------------------- // エスクロー情報:Escrow // ------------------------------------------------------------------- struct Escrow { address token; // トークンアドレス address sender; // 送信者 address recipient; // 受信者 uint256 amount; // 数量 address agent; // エスクローエージェント bool valid; // 有効状態 } /// エスクロー情報 /// escrowId => Escrow mapping(uint256 => Escrow) private escrow; /// 直近エスクローID uint256 private latestEscrowId = 0; /// @notice 直近エスクローIDの更新 /// @dev 最新バージョンのExchangeコントラクトのみ実行が可能 /// @param _latestEscrowId 直近エスクローID function setLatestEscrowId(uint256 _latestEscrowId) public onlyLatestVersion() { latestEscrowId = _latestEscrowId; } /// @notice 直近エスクローIDの参照 /// @return 直近エスクローID function getLatestEscrowId() public view returns(uint256) { return latestEscrowId; } /// @notice エスクロー情報の更新 /// @param _escrowId エスクローID /// @param _token トークンアドレス /// @param _sender 送信者 /// @param _recipient 受信者 /// @param _amount 数量 /// @param _agent エスクローエージェント /// @param _valid 有効状態 function setEscrow( uint256 _escrowId, address _token, address _sender, address _recipient, uint256 _amount, address _agent, bool _valid ) public onlyLatestVersion() { escrow[_escrowId].token = _token; escrow[_escrowId].sender = _sender; escrow[_escrowId].recipient = _recipient; escrow[_escrowId].amount = _amount; escrow[_escrowId].agent = _agent; escrow[_escrowId].valid = _valid; } /// @notice エスクロー情報の取得 /// @param _escrowId エスクローID /// @return token トークンアドレス /// @return sender 送信者 /// @return recipient 受信者 /// @return amount 数量 /// @return agent エスクローエージェント /// @return valid 有効状態 function getEscrow( uint256 _escrowId ) public view returns( address token, address sender, address recipient, uint256 amount, address agent, bool valid ) { return ( escrow[_escrowId].token, escrow[_escrowId].sender, escrow[_escrowId].recipient, escrow[_escrowId].amount, escrow[_escrowId].agent, escrow[_escrowId].valid ); } // ------------------------------------------------------------------- // 移転承諾関連機能 // ------------------------------------------------------------------- /// 移転申請 struct ApplicationForTransfer { address token; // トークンアドレス string applicationData; // 移転申請データ string approvalData; // 移転承認データ bool valid; // 申請有効状態 bool approved; // 移転承認状態 } mapping(uint256 => ApplicationForTransfer) private applicationsForTransfer; /// @notice 移転申請情報更新 /// @param _escrowId エスクローID /// @param _token トークンアドレス /// @param _applicationData 移転申請データ /// @param _approvalData 移転承認データ /// @param _valid 申請有効状態 /// @param _approved 移転承認状態 function setApplicationForTransfer( uint256 _escrowId, address _token, string memory _applicationData, string memory _approvalData, bool _valid, bool _approved ) public onlyLatestVersion() { applicationsForTransfer[_escrowId].token = _token; applicationsForTransfer[_escrowId].applicationData = _applicationData; applicationsForTransfer[_escrowId].approvalData = _approvalData; applicationsForTransfer[_escrowId].valid = _valid; applicationsForTransfer[_escrowId].approved = _approved; } /// @notice 移転申請情報参照 /// @param _escrowId エスクローID /// @return token トークンアドレス /// @return applicationData 移転申請データ /// @return approvalData 移転承認データ /// @return valid 申請有効状態 /// @return approved 移転承認状態 function getApplicationForTransfer( uint256 _escrowId ) public view returns( address token, string memory applicationData, string memory approvalData, bool valid, bool approved ) { return ( applicationsForTransfer[_escrowId].token, applicationsForTransfer[_escrowId].applicationData, applicationsForTransfer[_escrowId].approvalData, applicationsForTransfer[_escrowId].valid, applicationsForTransfer[_escrowId].approved ); } }
エスクロー情報の取得 _escrowId エスクローID return token トークンアドレス return sender 送信者 return recipient 受信者 return amount 数量 return agent エスクローエージェント return valid 有効状態
function getEscrow( uint256 _escrowId ) public view returns( address token, address sender, address recipient, uint256 amount, address agent, bool valid ) { return ( escrow[_escrowId].token, escrow[_escrowId].sender, escrow[_escrowId].recipient, escrow[_escrowId].amount, escrow[_escrowId].agent, escrow[_escrowId].valid ); }
5,423,410
pragma solidity ^0.4.21; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract Lockable is Owned { bool public isLocked = false; modifier checkLock(address from) { require(!isLocked || from == owner); _; } function lock() public onlyOwner returns (bool success) { isLocked = true; return true; } function unLock() public onlyOwner returns (bool success) { isLocked = false; return true; } } contract DreamToken is ERC20Interface, Owned, Lockable, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public maxSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function DreamToken() public { symbol = "DREAM"; name = "Dream"; decimals = 8; maxSupply = 21000000 * 10**8; totalSupply = maxSupply; balances[msg.sender] = maxSupply; } function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public checkLock(msg.sender) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public checkLock(from) returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function() public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Transfer tokens from the from account to the to account The calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public checkLock(from) returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
5,803,720
./full_match/1/0x3596fB4e61dE7d5Cca41Ae5a3fFFcCdedE313a4e/sources/src/CCIPeth.sol
Set new contract admin Admin only operation _admin New address for contract admin
function setAdmin(address _admin) external onlyAdmin { admin = _admin; emit AdminSet(_admin); }
3,132,961
/* * ERC20Lib - ERC20 standard implementation * * Copyright © 2018 by NewCryptoBlock. * * Based on Smart Contract Token System by Monerium * https://github.com/monerium/smart-contracts * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). */ pragma solidity ^0.4.11; import "./SafeMathLib.sol"; import "../helper/TokenRecipient.sol"; import "../controller/TokenStorage.sol"; library ERC20Lib { using SafeMathLib for uint; // EVENTS /** * @dev Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); // EXTERNAL /** * @dev Transfer given number of tokens from message sender to given recipient. * * @param db token storage * @param _caller address * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(TokenStorage db, address _caller, address _to, uint256 _value) returns (bool) { db.subBalance(_caller, _value); db.addBalance(_to, _value); Transfer(_caller, address(db), _value); return true; } /** * @dev Transfer given number of tokens from given owner to given recipient. * * @param db storage * @param _caller address * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(TokenStorage db, address _caller, address _from, address _to, uint256 _value) returns (bool success) { var allowance = db.getAllowed(_from, _caller); db.subBalance(_from, _value); db.addBalance(_to, _value); db.setAllowed(_from, _caller, allowance.minus(_value)); Transfer(_from, _to, _value); return true; } /** * @dev Allow given spender to transfer given number of tokens from message sender. * * @param db storage * @param _caller address * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve(TokenStorage db, address _caller, address _spender, uint256 _value) returns (bool success) { db.setAllowed(_caller, _spender, _value); Approval(_caller, _spender, _value); return true; } /** * @dev Approve and then communicate the approved contract in a single transaction * * @param db storage * @param _caller address * @param _spender Address of token spender. * @param _value Amount. * @param _extraData bytes */ function approveAndCall(TokenStorage db, address _caller, address _spender, uint256 _value, bytes _extraData) returns (bool success) { TokenRecipient spender = TokenRecipient(_spender); if (approve(db, _caller, _spender, _value)) { spender.receiveApproval(_caller, _value, this, _extraData); return true; } } // EXTERNAL CONSTANT function balanceOf(TokenStorage db, address _owner) constant returns (uint256 balance) { return db.getBalance(_owner); } function allowance(TokenStorage db, address _owner, address _spender) constant returns (uint256 remaining) { return db.getAllowed(_owner, _spender); } }
Transfer given number of tokens from given owner to given recipient. db storage _caller address _from address to transfer tokens from the owner of _to address to transfer tokens to the owner of _value number of tokens to transfer from given owner to given recipient return true if tokens were transferred successfully, false otherwise/
function transferFrom(TokenStorage db, address _caller, address _from, address _to, uint256 _value) returns (bool success) { var allowance = db.getAllowed(_from, _caller); db.subBalance(_from, _value); db.addBalance(_to, _value); db.setAllowed(_from, _caller, allowance.minus(_value)); Transfer(_from, _to, _value); return true; }
5,497,525
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../../Vault/Utils/Address.sol"; import "../../Vault/Utils/SafeBEP20.sol"; import "../../Vault/Utils/IBEP20.sol"; import "../../Vault/Utils/ReentrancyGuard.sol"; import "./XVSVaultStrategyProxy.sol"; import "./XVSVaultStrategyStorage.sol"; // This contract acts as a wrapper for user wallet interaction with the XVS Vault contract XVSVault is XVSVaultItemStorage, ReentrancyGuard { using SafeMath for uint256; using SafeBEP20 for IBEP20; using Address for address; modifier onlyAdminVault() { require(msg.sender == adminVault, "only admin vault can"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } function deposit(uint256 amount) external nonReentrant onlyAdminVault { IBEP20(xvs).approve(xvsVault, 2**256 - 1); IXVSVault(xvsVault).deposit(xvs, pid, amount); } function requestWithdrawal(uint256 amount) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).requestWithdrawal(xvs, pid, amount); } function claimRewards(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).deposit(xvs, pid, 0); // Transfer claimed XVS to the user wallet IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); } function compoundRewards() external nonReentrant onlyAdminVault { // claim the pending rewards IXVSVault(xvsVault).deposit(xvs, pid, 0); // deposit the claimed rewards back to the XVS Vault IXVSVault(xvsVault).deposit(xvs, pid, IBEP20(xvs).balanceOf(address(this))); } function executeWithdrawal(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).executeWithdrawal(xvs, pid); // Transfer XVS to user wallet IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); } /*** Admin Functions ***/ function _become(XVSVaultStrategyProxy xvsVaultStrategyProxy) public { require(msg.sender == xvsVaultStrategyProxy.admin(), "only proxy admin can change brains"); xvsVaultStrategyProxy._acceptImplementation(); } // Only allow to set the admin vault once. function setAdminVault(address _adminVault) external nonReentrant { require(_adminVault != address(0), "Zero address"); require(_adminVault.isContract(), "call to non-XVSVaultStrategy contract"); require(adminVault == address(0), "Admin vault is already set"); adminVault = _adminVault; } function emergencyWithdraw() external nonReentrant onlyAdmin { uint256 eligibleWithdrawalAmount = IXVSVault(xvsVault).getEligibleWithdrawalAmount(xvs, pid, address(this)); if (eligibleWithdrawalAmount > 0) { // Transfer the staked XVS from user vault contract to the user wallet IXVSVault(xvsVault).executeWithdrawal(xvs, pid); } // calculate the current available amount which is not yet requested to be withdrawn (uint256 amount, , uint256 pendingWithdrawals) = IXVSVault(xvsVault).getUserInfo(xvs, pid, address(this)); uint256 stakeAmount = amount.sub(pendingWithdrawals); if (stakeAmount > 0) { IXVSVault(xvsVault).requestWithdrawal(xvs, pid, stakeAmount); } // Transfer XVS to admin wallet IBEP20(xvs).safeTransferFrom(address(this), admin, IBEP20(xvs).balanceOf(address(this))); } }
Transfer XVS to user wallet
function executeWithdrawal(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).executeWithdrawal(xvs, pid); IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); }
2,492,535
pragma solidity ^0.4.17; // ---------------------------------------------------------------------------- // GAT Ownership Contract // // Copyright (c) 2017 GAT Systems Ltd. // http://www.gatcoin.io/ // // The MIT Licence. // ---------------------------------------------------------------------------- // Implementation of a simple ownership model with transfer acceptance. // contract Owned { address public owner; address public newOwner; event OwnerChanged(address indexed _newOwner); function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); require(_newOwner != owner); newOwner = _newOwner; return true; } function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); owner = msg.sender; OwnerChanged(msg.sender); return true; } } pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.17; // ---------------------------------------------------------------------------- // GAT Token ERC20 Interface // // Copyright (c) 2017 GAT Systems Ltd. // http://www.gatcoin.io/ // // The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC20 Standard Interface as specified at: // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract ERC20Interface { uint256 public totalSupply; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } pragma solidity ^0.4.17; // ---------------------------------------------------------------------------- // GAT Token Implementation // // Copyright (c) 2017 GAT Systems Ltd. // http://www.gatcoin.io/ // // The MIT Licence. // ---------------------------------------------------------------------------- // Implementation of standard ERC20 token with ownership. // contract GATToken is ERC20Interface, Owned { using SafeMath for uint256; string public symbol; string public name; uint256 public decimals; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; function GATToken(string _symbol, string _name, uint256 _decimals, uint256 _totalSupply) public Owned() { symbol = _symbol; name = _name; decimals = _decimals; totalSupply = _totalSupply; Transfer(0x0, owner, _totalSupply); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } pragma solidity ^0.4.17; // ---------------------------------------------------------------------------- // GAT Token Sale Configuration // // Copyright (c) 2017 GAT Systems Ltd. // http://www.gatcoin.io/ // // The MIT Licence. // ---------------------------------------------------------------------------- contract GATTokenSaleConfig { string public constant SYMBOL = "GAT"; string public constant NAME = "GAT Token"; uint256 public constant DECIMALS = 18; uint256 public constant DECIMALSFACTOR = 10**uint256(DECIMALS); uint256 public constant START_TIME = 1509192000; // 28-Oct-2017, 12:00:00 UTC uint256 public constant END_TIME = 1511870399; // 28-Nov-2017, 11:59:59 UTC uint256 public constant CONTRIBUTION_MIN = 0.1 ether; uint256 public constant TOKEN_TOTAL_CAP = 1000000000 * DECIMALSFACTOR; uint256 public constant TOKEN_PRIVATE_SALE_CAP = 70000000 * DECIMALSFACTOR; uint256 public constant TOKEN_PRESALE_CAP = 15000000 * DECIMALSFACTOR; uint256 public constant TOKEN_PUBLIC_SALE_CAP = 130000000 * DECIMALSFACTOR; // This also includes presale uint256 public constant TOKEN_FOUNDATION_CAP = 100000000 * DECIMALSFACTOR; uint256 public constant TOKEN_RESERVE1_CAP = 50000000 * DECIMALSFACTOR; uint256 public constant TOKEN_RESERVE2_CAP = 50000000 * DECIMALSFACTOR; uint256 public constant TOKEN_FUTURE_CAP = 600000000 * DECIMALSFACTOR; // Default bonus amount for the presale. // 100 = no bonus // 120 = 20% bonus. // Note that the owner can change the amount of bonus given. uint256 public constant PRESALE_BONUS = 120; // Default value for tokensPerKEther based on ETH at 300 USD. // The owner can update this value before the sale starts based on the // price of ether at that time. // E.g. 300 USD/ETH -> 300,000 USD/KETH / 0.2 USD/TOKEN = 1,500,000 uint256 public constant TOKENS_PER_KETHER = 1500000; } pragma solidity ^0.4.17; // ---------------------------------------------------------------------------- // GAT Token Sample Implementation // // Copyright (c) 2017 GAT Systems Ltd. // http://www.gatcoin.io/ // // The MIT Licence. // ---------------------------------------------------------------------------- // This is the main contract that drives the GAT token sale. // It exposes the ERC20 interface along with various sale-related functions. // contract GATTokenSale is GATToken, GATTokenSaleConfig { using SafeMath for uint256; // Once finalized, tokens will be freely tradable bool public finalized; // Sale can be suspended or resumed by the owner bool public suspended; // Addresses for the bank, funding and reserves. address public bankAddress; address public fundingAddress; address public reserve1Address; address public reserve2Address; // Price of tokens per 1000 ETH uint256 public tokensPerKEther; // The bonus amount on token purchases // E.g. 120 means a 20% bonus will be applied. uint256 public bonus; // Total number of tokens that have been sold through the sale contract so far. uint256 public totalTokensSold; // Keep track of start time and end time for the sale. These have default // values when the contract is deployed but can be changed by owner as needed. uint256 public startTime; uint256 public endTime; // Events event TokensPurchased(address indexed beneficiary, uint256 cost, uint256 tokens); event TokensPerKEtherUpdated(uint256 newAmount); event BonusAmountUpdated(uint256 newAmount); event TimeWindowUpdated(uint256 newStartTime, uint256 newEndTime); event SaleSuspended(); event SaleResumed(); event TokenFinalized(); event ContractTokensReclaimed(uint256 amount); function GATTokenSale(address _bankAddress, address _fundingAddress, address _reserve1Address, address _reserve2Address) public GATToken(SYMBOL, NAME, DECIMALS, 0) { // Can only create the contract is the sale has not yet started or ended. require(START_TIME >= currentTime()); require(END_TIME > START_TIME); // Need valid wallet addresses require(_bankAddress != address(0x0)); require(_bankAddress != address(this)); require(_fundingAddress != address(0x0)); require(_fundingAddress != address(this)); require(_reserve1Address != address(0x0)); require(_reserve1Address != address(this)); require(_reserve2Address != address(0x0)); require(_reserve2Address != address(this)); uint256 salesTotal = TOKEN_PUBLIC_SALE_CAP.add(TOKEN_PRIVATE_SALE_CAP); require(salesTotal.add(TOKEN_FUTURE_CAP).add(TOKEN_FOUNDATION_CAP).add(TOKEN_RESERVE1_CAP).add(TOKEN_RESERVE2_CAP) == TOKEN_TOTAL_CAP); // Start in non-finalized state finalized = false; suspended = false; // Start and end times (used for presale). startTime = START_TIME; endTime = END_TIME; // Initial pricing tokensPerKEther = TOKENS_PER_KETHER; // Bonus for contributions bonus = PRESALE_BONUS; // Initialize wallet addresses bankAddress = _bankAddress; fundingAddress = _fundingAddress; reserve1Address = _reserve1Address; reserve2Address = _reserve2Address; // Assign initial balances balances[address(this)] = balances[address(this)].add(TOKEN_PRESALE_CAP); totalSupply = totalSupply.add(TOKEN_PRESALE_CAP); Transfer(0x0, address(this), TOKEN_PRESALE_CAP); balances[reserve1Address] = balances[reserve1Address].add(TOKEN_RESERVE1_CAP); totalSupply = totalSupply.add(TOKEN_RESERVE1_CAP); Transfer(0x0, reserve1Address, TOKEN_RESERVE1_CAP); balances[reserve2Address] = balances[reserve2Address].add(TOKEN_RESERVE2_CAP); totalSupply = totalSupply.add(TOKEN_RESERVE2_CAP); Transfer(0x0, reserve2Address, TOKEN_RESERVE2_CAP); uint256 bankBalance = TOKEN_TOTAL_CAP.sub(totalSupply); balances[bankAddress] = balances[bankAddress].add(bankBalance); totalSupply = totalSupply.add(bankBalance); Transfer(0x0, bankAddress, bankBalance); // The total supply that we calculated here should be the same as in the config. require(balanceOf(address(this)) == TOKEN_PRESALE_CAP); require(balanceOf(reserve1Address) == TOKEN_RESERVE1_CAP); require(balanceOf(reserve2Address) == TOKEN_RESERVE2_CAP); require(balanceOf(bankAddress) == bankBalance); require(totalSupply == TOKEN_TOTAL_CAP); } function currentTime() public constant returns (uint256) { return now; } // Allows the owner to change the price for tokens. // function setTokensPerKEther(uint256 _tokensPerKEther) external onlyOwner returns(bool) { require(_tokensPerKEther > 0); // Set the tokensPerKEther amount for any new sale. tokensPerKEther = _tokensPerKEther; TokensPerKEtherUpdated(_tokensPerKEther); return true; } // Allows the owner to change the bonus amount applied to purchases. // function setBonus(uint256 _bonus) external onlyOwner returns(bool) { // 100 means no bonus require(_bonus >= 100); // 200 means 100% bonus require(_bonus <= 200); bonus = _bonus; BonusAmountUpdated(_bonus); return true; } // Allows the owner to change the time window for the sale. // function setTimeWindow(uint256 _startTime, uint256 _endTime) external onlyOwner returns(bool) { require(_startTime >= START_TIME); require(_endTime > _startTime); startTime = _startTime; endTime = _endTime; TimeWindowUpdated(_startTime, _endTime); return true; } // Allows the owner to suspend / stop the sale. // function suspend() external onlyOwner returns(bool) { if (suspended == true) { return false; } suspended = true; SaleSuspended(); return true; } // Allows the owner to resume the sale. // function resume() external onlyOwner returns(bool) { if (suspended == false) { return false; } suspended = false; SaleResumed(); return true; } // Accept ether contributions during the token sale. // function () payable public { buyTokens(msg.sender); } // Allows the caller to buy tokens for another recipient (proxy purchase). // This can be used by exchanges for example. // function buyTokens(address beneficiary) public payable returns (uint256) { require(!suspended); require(beneficiary != address(0x0)); require(beneficiary != address(this)); require(currentTime() >= startTime); require(currentTime() <= endTime); require(msg.value >= CONTRIBUTION_MIN); require(msg.sender != fundingAddress); // Check if the sale contract still has tokens for sale. uint256 saleBalance = balanceOf(address(this)); require(saleBalance > 0); // Calculate the number of tokens that the ether should convert to. uint256 tokens = msg.value.mul(tokensPerKEther).mul(bonus).div(10**(18 - DECIMALS + 3 + 2)); require(tokens > 0); uint256 cost = msg.value; uint256 refund = 0; if (tokens > saleBalance) { // Not enough tokens left for sale to fulfill the full order. tokens = saleBalance; // Calculate the actual cost for the tokens that can be purchased. cost = tokens.mul(10**(18 - DECIMALS + 3 + 2)).div(tokensPerKEther.mul(bonus)); // Calculate the amount of ETH refund to the contributor. refund = msg.value.sub(cost); } totalTokensSold = totalTokensSold.add(tokens); // Move tokens from the sale contract to the beneficiary balances[address(this)] = balances[address(this)].sub(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); Transfer(address(this), beneficiary, tokens); if (refund > 0) { msg.sender.transfer(refund); } // Transfer the contributed ether to the crowdsale wallets. uint256 contribution = msg.value.sub(refund); uint256 reserveAllocation = contribution.div(20); fundingAddress.transfer(contribution.sub(reserveAllocation)); reserve1Address.transfer(reserveAllocation); TokensPurchased(beneficiary, cost, tokens); return tokens; } // ERC20 transfer function, modified to only allow transfers once the sale has been finalized. // function transfer(address _to, uint256 _amount) public returns (bool success) { if (!isTransferAllowed(msg.sender, _to)) { return false; } return super.transfer(_to, _amount); } // ERC20 transferFrom function, modified to only allow transfers once the sale has been finalized. // function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { if (!isTransferAllowed(_from, _to)) { return false; } return super.transferFrom(_from, _to, _amount); } // Internal helper to check if the transfer should be allowed // function isTransferAllowed(address _from, address _to) private view returns (bool) { if (finalized) { // We allow everybody to transfer tokens once the sale is finalized. return true; } if (_from == bankAddress || _to == bankAddress) { // We allow the bank to initiate transfers. We also allow it to be the recipient // of transfers before the token is finalized in case a recipient wants to send // back tokens. E.g. KYC requirements cannot be met. return true; } return false; } // Allows owner to transfer tokens assigned to the sale contract, back to the bank wallet. function reclaimContractTokens() external onlyOwner returns (bool) { uint256 tokens = balanceOf(address(this)); if (tokens == 0) { return false; } balances[address(this)] = balances[address(this)].sub(tokens); balances[bankAddress] = balances[bankAddress].add(tokens); Transfer(address(this), bankAddress, tokens); ContractTokensReclaimed(tokens); return true; } // Allows the owner to finalize the sale and allow tokens to be traded. // function finalize() external onlyOwner returns (bool) { require(!finalized); finalized = true; TokenFinalized(); return true; } }
Allows the owner to finalize the sale and allow tokens to be traded.
function finalize() external onlyOwner returns (bool) { require(!finalized); finalized = true; TokenFinalized(); return true; }
5,348,442
/** *Submitted for verification at Etherscan.io on 2022-01-23 */ /** Telegram : https://t.me/buttholeinuerc20 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transacgtion ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract ButtHoleINU is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Butt Hole INU", "Butt Hole") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 8; uint256 _buyLiquidityFee = 7; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 15; uint256 _sellLiquidityFee = 10; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; //maxTransactionAmount = totalSupply * 50 / 1000; // 0.50% maxTransactionAmountTxn maxTransactionAmount = 5000000000 * 1e18; maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet swapTokensAtAmount = totalSupply * 15 / 10000; // 0.15% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
maxTransactionAmount = totalSupply 50 / 1000; 0.50% maxTransactionAmountTxn exclude from paying fees or having max transaction amount
constructor() ERC20("Butt Hole INU", "Butt Hole") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 8; uint256 _buyLiquidityFee = 7; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 15; uint256 _sellLiquidityFee = 10; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = 5000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,641,761
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; pragma abicoder v2; import './Ownable.sol'; contract Store is Ownable { struct BoughtProduct { string productType; bool isBought; uint blockNum; } // Storing products and their quantity in a mapping mapping(string => uint) products; mapping(string => bool) existingProducts; string[] productTypes; // Storing the bought products by clients in a nested mapping mapping(address => mapping(string => BoughtProduct)) boughtProducts; mapping(string => address[]) productBuyers; // Add a product to the store (owner only) function addProduct(string memory productType, uint quantity) external onlyOwner { products[productType] += quantity; if (!existingProducts[productType]) { existingProducts[productType] = true; productTypes.push(productType); } } modifier onlyExisting (string memory productType) { require(existingProducts[productType], "Product doesn't exist"); _; } // Buy a product function buyProduct(string memory productType) external onlyExisting(productType) { require(products[productType] > 0, "Insufficient Quantity"); address buyer = msg.sender; uint blockNum = block.number; require(!boughtProducts[buyer][productType].isBought, "Customer already has this product"); boughtProducts[buyer][productType] = BoughtProduct(productType, true, blockNum); productBuyers[productType].push(buyer); products[productType] -= 1; } // Return a product function returnProduct(string memory productType) external onlyExisting(productType) { address buyer = msg.sender; uint blockNum = block.number; require(boughtProducts[buyer][productType].isBought, "Customer doesn't own this product"); require(blockNum - boughtProducts[buyer][productType].blockNum < 100, "Too late to return product"); delete boughtProducts[buyer][productType]; products[productType]++; } // View the addresses of clients that have bought a certain product function getProductBuyers(string memory productType) external view onlyExisting(productType) returns (address[] memory) { return productBuyers[productType]; } // View products in store function getProductTypes() external view returns (string[] memory) { return productTypes; } }
View the addresses of clients that have bought a certain product
function getProductBuyers(string memory productType) external view onlyExisting(productType) returns (address[] memory) { return productBuyers[productType]; }
12,991,077
pragma solidity 0.5.10; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IMarket } from "./IMarket.sol"; import { IVault } from "../vault/IVault.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { ICurveFunctions } from "../_curveIntegrals/v1/ICurveFunctions.sol"; /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Creation and storage of project tokens, fills vault with fee. * @notice The market will send a portion of all collateral on mint to the * vault to fill the funding rounds. * @dev Checks with vault on every mint to ensure rounds are still active, * goal has not been met, and that the round has not expired. */ contract Market is IMarket, IERC20 { // For math functions with overflow & underflow checks using SafeMath for uint256; // Allows market to be deactivated after funding bool internal active_ = true; // Vault that recives fee IVault internal creatorVault_; // Percentage of vault fee e.g. 20 uint256 internal feeRate_; // Address of curve function ICurveFunctions internal curveLibrary_; // Underlying collateral token IERC20 internal collateralToken_; // Total minted tokens uint256 internal totalSupply_; // Decimal accuracy of token uint256 internal decimals_ = 18; // Allowances for spenders mapping(address => mapping (address => uint256)) internal allowed; // Balances of token holders mapping(address => uint256) internal balances; /** * @notice Sets the needed variables for the market * @param _feeRate : The percentage for the fee i.e 20 * @param _creatorVault : The vault for fee to go to * @param _curveLibrary : Math module. * @param _collateralToken : The ERC20 collateral tokem */ constructor( uint256 _feeRate, address _creatorVault, address _curveLibrary, address _collateralToken ) public { // Sets the storage variables feeRate_ = _feeRate; creatorVault_ = IVault(_creatorVault); curveLibrary_ = ICurveFunctions(_curveLibrary); collateralToken_ = IERC20(_collateralToken); } /** * @notice Ensures the market's key functionality is only available when * the market is active. */ modifier onlyActive(){ require(active_, "Market inactive"); _; } /** * @notice Enaures a function is only callable by the vault. */ modifier onlyVault(){ require(msg.sender == address(creatorVault_), "Invalid requestor"); _; } /** * @dev Selling tokens back to the bonding curve for collateral. * @param _numTokens: The number of tokens that you want to burn. */ function burn(uint256 _numTokens) external onlyActive() returns(bool) { require( balances[msg.sender] >= _numTokens, "Not enough tokens available" ); uint256 reward = rewardForBurn(_numTokens); totalSupply_ = totalSupply_.sub(_numTokens); balances[msg.sender] = balances[msg.sender].sub(_numTokens); require( collateralToken_.transfer( msg.sender, reward ), "Tokens not sent" ); emit Transfer(msg.sender, address(0), _numTokens); emit Burn(msg.sender, _numTokens, reward); return true; } /** * @dev We have modified the minting function to divert a portion of the * collateral for the purchased tokens to the vault. * @notice If a mint transaction exceeded the needed funding for the last * round, the excess funds WILL NOT BE RETURNED TO SENDER. The * Molecule Catalyst front end prevents this. * The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _to : Address to mint tokens to. * @param _numTokens : The number of tokens you want to mint. */ function mint( address _to, uint256 _numTokens ) external onlyActive() returns(bool) { // Gets the price (in collateral) for the tokens uint256 priceForTokens = priceToMint(_numTokens); // Ensures there is no overflow require(priceForTokens > 0, "Tokens requested too low"); // Works out how much fee needs to be sent to the vault uint256 fee = priceForTokens.mul(feeRate_).div(100); // Sends the collateral from the buyer to this market require( collateralToken_.transferFrom( msg.sender, address(this), priceForTokens ), "Collateral transfer failed" ); // Sends the fee to the vault require( collateralToken_.transfer( address(creatorVault_), fee ), "Vault fee not transferred" ); // Adds the tokens to the total supply totalSupply_ = totalSupply_.add(_numTokens); // Adds the tokens to the balance of the buyer balances[msg.sender] = balances[msg.sender].add(_numTokens); // Validates the funding with the vault require( creatorVault_.validateFunding(fee), "Funding validation failed" ); // Works out the vaule of the tokens without the fee uint256 priceWithoutFee = priceForTokens.sub(fee); emit Transfer(address(0), _to, _numTokens); emit Mint(_to, _numTokens, priceWithoutFee, fee); return true; } /** * @notice This function returns the amount of tokens one can receive for a * specified amount of collateral token. * @param _collateralTokenOffered : Amount of reserve token offered for * purchase. * @return uint256 : The amount of tokens once can purchase with the * specified collateral. */ function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256) { // Works out the amount of collateral for fee uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100); // Removes the fee amount from the collateral offered uint256 amountLessFee = _collateralTokenOffered.sub(fee); // Works out the inverse curve of the pool with the fee removed amount return _inverseCurveIntegral( _curveIntegral(totalSupply_).add(amountLessFee) ).sub(totalSupply_); } /** * @notice This function returns the amount of tokens needed to be burnt to * withdraw a specified amount of reserve token. * @param _collateralTokenNeeded : Amount of dai to be withdraw. */ function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256) { return uint256( totalSupply_.sub( _inverseCurveIntegral( _curveIntegral(totalSupply_).sub(_collateralTokenNeeded) ) ) ); } /** * @notice Total collateral backing the curve. * @return uint256 : Represents the total collateral backing the curve. */ function poolBalance() external view returns (uint256){ return collateralToken_.balanceOf(address(this)); } /** * @dev The rate of fee the market pays towards the vault on token * purchases. */ function feeRate() external view returns(uint256) { return feeRate_; } /** * @return uint256 : The decimals set for the market */ function decimals() external view returns(uint256) { return decimals_; } /** * @return bool : The active stat of the market. Inactive markets have * ended. */ function active() external view returns(bool){ return active_; } /** * @notice Can only be called by this markets vault * @dev Allows the market to end once all funds have been raised. * Ends the market so that no more tokens can be bought or sold. * Tokens can still be transfered, or "withdrawn" for an enven * distribution of remaining collateral. */ function finaliseMarket() public onlyVault() returns(bool) { require(active_, "Market deactivated"); active_ = false; emit MarketTerminated(); return true; } /** * @dev Allows token holders to withdraw collateral in return for tokens * after the market has been finalised. * @param _amount: The amount of tokens they want to withdraw */ function withdraw(uint256 _amount) public returns(bool) { // Ensures withdraw can only be called in an inactive market require(!active_, "Market not finalised"); // Ensures the sender has enough tokens require(_amount <= balances[msg.sender], "Insufficient funds"); // Ensures there are no anomaly withdraws that might break calculations require(_amount > 0, "Cannot withdraw 0"); // Removes amount from user balance balances[msg.sender] = balances[msg.sender].sub(_amount); // Gets the balance of the market (vault may send excess funding) uint256 balance = collateralToken_.balanceOf(address(this)); // Performs a flat linear 100% collateralized sale uint256 collateralToTransfer = balance.mul(_amount).div(totalSupply_); // Removes token amount from the total supply totalSupply_ = totalSupply_.sub(_amount); // Ensures the sender is sent their collateral amount require( collateralToken_.transfer(msg.sender, collateralToTransfer), "Dai transfer failed" ); emit Transfer(msg.sender, address(0), _amount); emit Burn(msg.sender, _amount, collateralToTransfer); return true; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens. * @notice The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _numTokens: The number of tokens to calculate the price of * @return uint256 : The required collateral amount for a volume of bonding * curve tokens. */ function priceToMint(uint256 _numTokens) public view returns(uint256) { // Gets the balance of the market uint256 balance = collateralToken_.balanceOf(address(this)); // Performs the curve intergral with the relavant vaules uint256 collateral = _curveIntegral( totalSupply_.add(_numTokens) ).sub(balance); // Sets the base unit for decimal shift uint256 baseUnit = 100; // Adds the fee amount uint256 result = collateral.mul(100).div(baseUnit.sub(feeRate_)); return result; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to work out the collateral * vaule of * @return uint256: The required collateral amount for a volume of bonding * curve tokens */ function rewardForBurn(uint256 _numTokens) public view returns(uint256) { // Gets the curent balance of the market uint256 poolBalanceFetched = collateralToken_.balanceOf(address(this)); // Returns the pool balance minus the curve intergral of the removed // tokens return poolBalanceFetched.sub( _curveIntegral(totalSupply_.sub(_numTokens)) ); } /** * @dev Calculate the integral from 0 to x tokens supply. Calls the * curve integral function on the math library. * @param _x : The number of tokens supply to integrate to. * @return he total supply in tokens, not wei. */ function _curveIntegral(uint256 _x) internal view returns (uint256) { return curveLibrary_.curveIntegral(_x); } /** * @dev Inverse integral to convert the incoming colateral value to * token volume. * @param _x : The volume to identify the root off */ function _inverseCurveIntegral(uint256 _x) internal view returns(uint256) { return curveLibrary_.inverseCurveIntegral(_x); } //-------------------------------------------------------------------------- // ERC20 functions //-------------------------------------------------------------------------- /** * @notice Total number of tokens in existence * @return uint256: Represents the total supply of tokens in this market. */ function totalSupply() external view returns (uint256) { return totalSupply_; } /** * @notice Gets the balance of the specified address. * @param _owner : The address to query the the balance of. * @return uint256 : Represents the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /** * @notice Gets the value of the current allowance specifed for that * account. * @param _owner: The account sending the funds. * @param _spender: The account that will receive the funds. * @return uint256: representing the amount the spender can spend */ function allowance( address _owner, address _spender ) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Approves transfers for a given address. * @param _spender : The account that will receive the funds. * @param _value : The value of funds accessed. * @return boolean : Indicating the action was successful. */ function approve( address _spender, uint256 _value ) external returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function increaseAllowance( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function decreaseAllowance( address _spender, uint256 _subtractedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .sub(_subtractedValue); emit Approval(msg.sender, _spender, _subtractedValue); return true; } /** * @notice Transfer tokens from one address to another. * @param _from : The address which you want to send tokens from. * @param _to : The address which you want to transfer to. * @param _value : The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Requested amount exceeds balance"); require(_value <= allowed[_from][msg.sender], "Allowance exceeded"); require(_to != address(0), "Target account invalid"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice Transfer ownership token from msg.sender to a specified address. * @param _to : The address to transfer to. * @param _value : The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "Insufficient funds"); require(_to != address(0), "Target account invalid"); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } }
This function returns the amount of tokens one can receive for a specified amount of collateral token. _collateralTokenOffered : Amount of reserve token offered for purchase. return uint256 : The amount of tokens once can purchase with the specified collateral./ Works out the amount of collateral for fee Removes the fee amount from the collateral offered Works out the inverse curve of the pool with the fee removed amount
function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256) { uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100); uint256 amountLessFee = _collateralTokenOffered.sub(fee); return _inverseCurveIntegral( _curveIntegral(totalSupply_).add(amountLessFee) ).sub(totalSupply_); }
7,319,239
/** *Submitted for verification at Etherscan.io on 2020-11-20 */ // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor(uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require( totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded" ); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol pragma solidity ^0.6.0; /** * @title IERC1363 Interface * @dev Interface for a Payable Token contract as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value ) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value, bytes calldata data ) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 value, bytes calldata data ) external returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol pragma solidity ^0.6.0; /** * @title IERC1363Receiver Interface * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived( address operator, address from, uint256 value, bytes calldata data ) external returns (bytes4); // solhint-disable-line max-line-length } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol pragma solidity ^0.6.0; /** * @title IERC1363Spender Interface * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived( address owner, uint256 value, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165Checker.sol pragma solidity ^0.6.2; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface( account, interfaceId ); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector( _INTERFACE_ID_ERC165, interfaceId ); (bool success, bytes memory result) = account.staticcall{gas: 30000}( encodedParams ); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public override view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: erc-payable-token/contracts/token/ERC1363/ERC1363.sol pragma solidity ^0.6.0; /** * @title ERC1363 * @dev Implementation of an ERC1363 interface */ contract ERC1363 is ERC20, IERC1363, ERC165 { using Address for address; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; // Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` // which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c; // Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` // which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector` bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0; /** * @param name Name of the token * @param symbol A symbol to be used as ticker */ constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { // register the supported interfaces to conform to ERC1363 via ERC165 _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER); _registerInterface(_INTERFACE_ID_ERC1363_APPROVE); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to. * @param value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferAndCall(address to, uint256 value) public override returns (bool) { return transferAndCall(to, value, ""); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to * @param value The amount to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferAndCall( address to, uint256 value, bytes memory data ) public override returns (bool) { transfer(to, value); require( _checkAndCallTransfer(_msgSender(), to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Transfer tokens from one address to another and then execute a callback on recipient. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value The amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFromAndCall( address from, address to, uint256 value ) public override returns (bool) { return transferFromAndCall(from, to, value, ""); } /** * @dev Transfer tokens from one address to another and then execute a callback on recipient. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value The amount of tokens to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferFromAndCall( address from, address to, uint256 value, bytes memory data ) public override returns (bool) { transferFrom(from, to, value); require( _checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to * @param value The amount allowed to be transferred * @return A boolean that indicates if the operation was successful. */ function approveAndCall(address spender, uint256 value) public override returns (bool) { return approveAndCall(spender, value, ""); } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to. * @param value The amount allowed to be transferred. * @param data Additional data with no specified format. * @return A boolean that indicates if the operation was successful. */ function approveAndCall( address spender, uint256 value, bytes memory data ) public override returns (bool) { approve(spender, value); require( _checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts" ); return true; } /** * @dev Internal function to invoke `onTransferReceived` on a target address * The call is not executed if the target address is not a contract * @param from address Representing the previous owner of the given token value * @param to address Target address that will receive the tokens * @param value uint256 The amount mount of tokens to be transferred * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallTransfer( address from, address to, uint256 value, bytes memory data ) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove( address spender, uint256 value, bytes memory data ) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.6.0; /** * @title TokenRecover * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant" ); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke" ); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require( account == _msgSender(), "AccessControl: can only renounce roles for self" ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/access/Roles.sol pragma solidity ^0.6.0; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } } // File: contracts/DGCLToken.sol pragma solidity ^0.6.0; // TOKEN NAME: DigiCol Token // SYMBOL: DGCL /** * @title DGCLToken * @dev Implementation of the DGCLToken */ contract DGCLToken is ERC20Capped, ERC20Burnable, ERC1363, Roles, TokenRecover { // indicates if minting is finished bool private _mintingFinished = false; // indicates if transfer is enabled bool private _transferEnabled = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Emitted during transfer enabling */ event TransferEnabled(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "DGCLToken: minting is finished"); _; } /** * @dev Tokens can be moved only after if transfer enabled or if you are an approved operator. */ modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "DGCLToken: transfer is not enabled or from does not have the OPERATOR role" ); _; } /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit * @param cap Maximum number of tokens mintable * @param initialSupply Initial token supply * @param transferEnabled If transfer is enabled on token creation * @param mintingFinished If minting is finished after token creation */ constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) public ERC20Capped(cap) ERC1363(name, symbol) { require( mintingFinished == false || cap == initialSupply, "DGCLToken: if finish minting, cap must be equal to initialSupply" ); _setupDecimals(decimals); if (initialSupply > 0) { _mint(owner(), initialSupply); } if (mintingFinished) { finishMinting(); } if (transferEnabled) { enableTransfer(); } } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @return if transfer is enabled or not. */ function transferEnabled() public view returns (bool) { return _transferEnabled; } /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens * @param value The amount of tokens to mint */ function mint(address to, uint256 value) public canMint onlyMinter { _mint(to, value); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to * @param value The amount to be transferred * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFrom( address from, address to, uint256 value ) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Function to stop minting new tokens. */ function finishMinting() public canMint onlyOwner { _mintingFinished = true; emit MintFinished(); } /** * @dev Function to enable transfers. */ function enableTransfer() public onlyOwner { _transferEnabled = true; emit TransferEnabled(); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } }
Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw account The address of the contract to query for support of an interface interfaceId The interface identifier, as specified in ERC-165 return success true if the STATICCALL succeeded, false otherwise return result true if the STATICCALL succeeded and the contract at account indicates support of the interface with identifier interfaceId, false otherwise/
function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector( _INTERFACE_ID_ERC165, interfaceId ); encodedParams ); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); }
2,274,980
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol'; /** * @title NewfiToken * @dev ERC20 token that automatically mints tokens based on the * proportional amount of ownership in a NewFi pool. * F = I * P * P = F / I * F = amount of tokens in the pool * I = amount of wrapped tokens held by investors * P = Price of the Wrapped Tokens */ contract NewfiToken is ERC20UpgradeSafe, OwnableUpgradeSafe { using SafeMath for uint256; /** * @dev initialize that gives holder all of existing tokens. */ function initialize(string memory name, string memory symbol) public initializer { OwnableUpgradeSafe.__Ownable_init(); ERC20UpgradeSafe.__ERC20_init(name, symbol); } /** * @dev mint new proof of ownership tokens. * Minted = Invest * (wrappedTokens / poolTokens) * At the start P = 1, therefore I = F, value = wrapped tokens */ function mintOwnershipTokens( address holder, uint256 poolTokens, uint256 toInvest ) public onlyOwner { require(poolTokens > 0); require(toInvest > 0); uint256 tokenDecimals = 10**uint256(decimals()); uint256 wrappedTokens = totalSupply() == 0 ? 1 : totalSupply().div(tokenDecimals); _mint( holder, (toInvest.mul(wrappedTokens).div(poolTokens)).mul(tokenDecimals) ); } }
mint new proof of ownership tokens. Minted = Invest (wrappedTokens / poolTokens) At the start P = 1, therefore I = F, value = wrapped tokens/
function mintOwnershipTokens( address holder, uint256 poolTokens, uint256 toInvest ) public onlyOwner { require(poolTokens > 0); require(toInvest > 0); uint256 tokenDecimals = 10**uint256(decimals()); uint256 wrappedTokens = totalSupply() == 0 ? 1 : totalSupply().div(tokenDecimals); _mint( holder, (toInvest.mul(wrappedTokens).div(poolTokens)).mul(tokenDecimals) ); }
1,001,831
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { IFLIStrategyAdapter } from "../interfaces/IFLIStrategyAdapter.sol"; import { IUniswapV2Router } from "../interfaces/IUniswapV2Router.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FLIRebalanceViewer * @author Set Protocol * * FLI Rebalance viewer that returns whether a Compound oracle update should be forced before a rebalance goes through, if no * oracle update the type of rebalance transaction will be returned adhering to the enum specified in FlexibleLeverageStrategyAdapter * * CHANGELOG: 4/28/2021 * - Enables calculating Uniswap price with any multihop route * - Lever and delever exchange data is read directly from strategy adapter and if not empty, calculate price based on encoded route */ contract FLIRebalanceViewer { using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum FLIRebalanceAction { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD, // Indicates ripcord() function can be successfully called ORACLE // Indicates Compound oracle update should be pushed } /* ============ State Variables ============ */ IUniswapV2Router public uniswapRouter; IFLIStrategyAdapter public strategyAdapter; address public cEther; /* ============ Constructor ============ */ constructor(IUniswapV2Router _uniswapRouter, IFLIStrategyAdapter _strategyAdapter, address _cEther) public { uniswapRouter = _uniswapRouter; strategyAdapter = _strategyAdapter; cEther = _cEther; } /* ============ External Functions ============ */ /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord(). Additionally, logic is added to check if an oracle update * should be forced to the Compound protocol ahead of the rebalance (4). * * @param _customMinLeverageRatio Min leverage ratio passed in by caller to trigger rebalance * @param _customMaxLeverageRatio Max leverage ratio passed in by caller to trigger rebalance * * return FLIRebalanceAction Enum detailing whether to do nothing, rebalance, iterateRebalance, ripcord, or update Compound oracle */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FLIRebalanceAction) { FlexibleLeverageStrategyAdapter.ShouldRebalance adapterRebalanceState = strategyAdapter.shouldRebalanceWithBounds( _customMinLeverageRatio, _customMaxLeverageRatio ); if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.NONE) { return FLIRebalanceAction.NONE; } else if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.RIPCORD) { FlexibleLeverageStrategyAdapter.IncentiveSettings memory incentive = strategyAdapter.getIncentive(); bool updateOracle = _shouldOracleBeUpdated(incentive.incentivizedTwapMaxTradeSize, incentive.incentivizedSlippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : FLIRebalanceAction.RIPCORD; } else { FlexibleLeverageStrategyAdapter.ExecutionSettings memory execution = strategyAdapter.getExecution(); FLIRebalanceAction rebalanceAction = adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.REBALANCE ? FLIRebalanceAction.REBALANCE : FLIRebalanceAction.ITERATE_REBALANCE; bool updateOracle = _shouldOracleBeUpdated(execution.twapMaxTradeSize, execution.slippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : rebalanceAction; } } /* ============ Internal Functions ============ */ /** * Checks if the Compound oracles should be updated before executing any rebalance action. Updates must occur if the resulting trade would end up outside the * slippage bounds as calculated against the Compound oracle. Aligning the oracle more closely with market prices should allow rebalances to go through. * * @param _maxTradeSize Max trade size of rebalance action (varies whether its ripcord or normal rebalance) * @param _slippageTolerance Slippage tolerance of rebalance action (varies whether its ripcord or normal rebalance) * * return bool Boolean indicating whether oracle needs to be updated */ function _shouldOracleBeUpdated( uint256 _maxTradeSize, uint256 _slippageTolerance ) internal view returns (bool) { FlexibleLeverageStrategyAdapter.ContractSettings memory settings = strategyAdapter.getStrategy(); uint256 executionPrice; uint256 oraclePrice; if (strategyAdapter.getCurrentLeverageRatio() > strategyAdapter.getMethodology().targetLeverageRatio) { executionPrice = _getUniswapExecutionPrice(settings.borrowAsset, settings.collateralAsset, _maxTradeSize, false); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetBorrowCToken, settings.targetCollateralCToken); } else { executionPrice = _getUniswapExecutionPrice(settings.collateralAsset, settings.borrowAsset, _maxTradeSize, true); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetCollateralCToken, settings.targetBorrowCToken); } return executionPrice > oraclePrice.preciseMul(PreciseUnitMath.preciseUnit().add(_slippageTolerance)); } /** * Calculates Uniswap exection price by querying Uniswap for expected token flow amounts for a trade and implying market price. Returned value * is normalized to 18 decimals. * * @param _buyAsset Asset being bought on Uniswap * @param _sellAsset Asset being sold on Uniswap * @param _tradeSize Size of the trade in collateral units * @param _isBuyingCollateral Whether collateral is being bought or sold (used to determine which Uniswap function to call) * * return uint256 Implied Uniswap market price for pair, normalized to 18 decimals */ function _getUniswapExecutionPrice( address _buyAsset, address _sellAsset, uint256 _tradeSize, bool _isBuyingCollateral ) internal view returns (uint256) { bytes memory pathCalldata = _isBuyingCollateral ? strategyAdapter.getExecution().leverExchangeData : strategyAdapter.getExecution().deleverExchangeData; address[] memory path; if(pathCalldata.length == 0){ path = new address[](2); path[0] = _sellAsset; path[1] = _buyAsset; } else { path = abi.decode(pathCalldata, (address[])); } // Returned [sellAmount, buyAmount] uint256[] memory flows = _isBuyingCollateral ? uniswapRouter.getAmountsIn(_tradeSize, path) : uniswapRouter.getAmountsOut(_tradeSize, path); uint256 buyDecimals = uint256(10)**ERC20(_buyAsset).decimals(); uint256 sellDecimals = uint256(10)**ERC20(_sellAsset).decimals(); uint256 lastIndex = path.length.sub(1); return flows[0].preciseDiv(sellDecimals).preciseDiv(flows[lastIndex].preciseDiv(buyDecimals)); } /** * Calculates Compound oracle price * * @param _priceOracle Compound price oracle * @param _cTokenBuyAsset CToken having net exposure increased (ie if net balance is short, decreasing short) * @param _cTokenSellAsset CToken having net exposure decreased (ie if net balance is short, increasing short) * * return uint256 Compound oracle price for pair, normalized to 18 decimals */ function _getCompoundOraclePrice( ICompoundPriceOracle _priceOracle, ICErc20 _cTokenBuyAsset, ICErc20 _cTokenSellAsset ) internal view returns (uint256) { uint256 buyPrice = _priceOracle.getUnderlyingPrice(address(_cTokenBuyAsset)); uint256 sellPrice = _priceOracle.getUnderlyingPrice(address(_cTokenSellAsset)); uint256 buyDecimals = address(_cTokenBuyAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenBuyAsset.underlying()).decimals(); uint256 sellDecimals = address(_cTokenSellAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenSellAsset.underlying()).decimals(); return buyPrice.mul(buyDecimals).preciseDiv(sellPrice.mul(sellDecimals)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { BaseAdapter } from "../lib/BaseAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FlexibleLeverageStrategyAdapter * @author Set Protocol * * Smart contract that enables trustless leverage tokens using the flexible leverage methodology. This adapter is paired with the CompoundLeverageModule from Set * protocol where module interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow * asset is available on Compound. This adapter contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance function at * different leverage thresholds. * * CHANGELOG 4/14/2021: * - Update ExecutionSettings struct to split exchangeData into leverExchangeData and deleverExchangeData * - Update _lever and _delever internal functions with struct changes * - Update setExecutionSettings to account for leverExchangeData and deleverExchangeData */ contract FlexibleLeverageStrategyAdapter is BaseAdapter { using Address for address; using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum ShouldRebalance { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD // Indicates ripcord() function can be successfully called } /* ============ Structs ============ */ struct ActionInfo { uint256 collateralPrice; // Price of underlying in precise units (10e18) uint256 borrowPrice; // Price of underlying in precise units (10e18) uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6) uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 setTotalSupply; // Total supply of SetToken } struct LeverageInfo { ActionInfo action; uint256 currentLeverageRatio; // Current leverage ratio of Set uint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16) uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance action } struct ContractSettings { ISetToken setToken; // Instance of leverage token ICompoundLeverageModule leverageModule; // Instance of Compound leverage module IComptroller comptroller; // Instance of Compound Comptroller ICompoundPriceOracle priceOracle; // Compound open oracle feed that returns prices accounting for decimals. e.g. USDC 6 decimals = 10^18 * 10^18 / 10^6 ICErc20 targetCollateralCToken; // Instance of target collateral cToken asset ICErc20 targetBorrowCToken; // Instance of target borrow cToken asset address collateralAsset; // Address of underlying collateral address borrowAsset; // Address of underlying borrow asset } struct MethodologySettings { uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18) uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratio uint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratio uint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18) uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds } struct ExecutionSettings { uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16) uint256 twapMaxTradeSize; // Max trade size in collateral base units uint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantities string exchangeName; // Name of exchange that is being used for leverage bytes leverExchangeData; // Arbitrary exchange data passed into rebalance function for levering up bytes deleverExchangeData; // Arbitrary exchange data passed into rebalance function for delevering } struct IncentiveSettings { uint256 etherReward; // ETH reward for incentivized rebalances uint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalances uint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalances uint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances uint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base units } /* ============ Events ============ */ event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event Rebalanced( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RebalanceIterated( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RipcordCalled( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _rebalanceNotional, uint256 _etherIncentive ); event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event MethodologySettingsUpdated( uint256 _targetLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio, uint256 _recenteringSpeed, uint256 _rebalanceInterval ); event ExecutionSettingsUpdated( uint256 _unutilizedLeveragePercentage, uint256 _twapMaxTradeSize, uint256 _twapCooldownPeriod, uint256 _slippageTolerance, string _exchangeName, bytes _leverExchangeData, bytes _deleverExchangeData ); event IncentiveSettingsUpdated( uint256 _etherReward, uint256 _incentivizedLeverageRatio, uint256 _incentivizedSlippageTolerance, uint256 _incentivizedTwapCooldownPeriod, uint256 _incentivizedTwapMaxTradeSize ); /* ============ Modifiers ============ */ /** * Throws if rebalance is currently in TWAP` */ modifier noRebalanceInProgress() { require(twapLeverageRatio == 0, "Rebalance is currently in progress"); _; } /* ============ State Variables ============ */ ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc) MethodologySettings internal methodology; // Struct containing methodology parameters ExecutionSettings internal execution; // Struct containing execution parameters IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcord uint256 public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalances uint256 public lastTradeTimestamp; // Last rebalance timestamp. Must be past rebalance interval to rebalance /* ============ Constructor ============ */ /** * Instantiate addresses, methodology parameters, execution parameters, and incentive parameters. * * @param _manager Address of IBaseManager contract * @param _strategy Struct of contract addresses * @param _methodology Struct containing methodology parameters * @param _execution Struct containing execution parameters * @param _incentive Struct containing incentive parameters for ripcord */ constructor( IBaseManager _manager, ContractSettings memory _strategy, MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) public BaseAdapter(_manager) { strategy = _strategy; methodology = _methodology; execution = _execution; incentive = _incentive; _validateSettings(methodology, execution, incentive); } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Compound and trade for collateral asset. If target * leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target * is met. */ function engage() external onlyOperator { ActionInfo memory engageInfo = _createActionInfo(); require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(engageInfo.borrowBalance == 0, "Debt must be 0"); LeverageInfo memory leverageInfo = LeverageInfo({ action: engageInfo, currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units slippageTolerance: execution.slippageTolerance, twapMaxTradeSize: execution.twapMaxTradeSize }); // Calculate total rebalance units and kick off TWAP if above max borrow or max trade size ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, totalRebalanceNotional, methodology.targetLeverageRatio ); emit Engaged( leverageInfo.currentLeverageRatio, methodology.targetLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Rebalance according to flexible leverage methodology. If current leverage ratio is between the max and min bounds, then rebalance * can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage * ratio back to the max or min bounds. The methodology will determine whether to delever or lever. * * Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call * ripcord() which is incentivized with a reward in Ether or iterateRebalance(). */ function rebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, methodology.rebalanceInterval); _validateNonTWAP(); uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _handleRebalance(leverageInfo, newLeverageRatio); _updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio); emit Rebalanced( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing * and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state. */ function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod); _validateTWAP(); uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) { (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio); } // If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is // cleared _updateIterateState(chunkRebalanceNotional, totalRebalanceNotional); emit RebalanceIterated( leverageInfo.currentLeverageRatio, twapLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio * back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller * of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically * looser than in regular rebalances. */ function ripcord() external onlyEOA { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo( incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapMaxTradeSize ); _validateRipcord(leverageInfo); ( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false); _delever(leverageInfo, chunkRebalanceNotional); _updateRipcordState(); uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward); emit RipcordCalled( leverageInfo.currentLeverageRatio, methodology.maxLeverageRatio, chunkRebalanceNotional, etherTransferred ); } /** * OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem * collateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function will * delever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator must * continue to call this function to complete repayment of loan. The function iterateRebalance will not work. * * Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch */ function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); } else { _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newMethodologySettings Struct containing methodology parameters */ function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); } /** * OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newExecutionSettings Struct containing execution parameters */ function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress { execution = _newExecutionSettings; _validateSettings(methodology, execution, incentive); emit ExecutionSettingsUpdated( execution.unutilizedLeveragePercentage, execution.twapMaxTradeSize, execution.twapCooldownPeriod, execution.slippageTolerance, execution.exchangeName, execution.leverExchangeData, execution.deleverExchangeData ); } /** * OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newIncentiveSettings Struct containing incentive parameters */ function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress { incentive = _newIncentiveSettings; _validateSettings(methodology, execution, incentive); emit IncentiveSettingsUpdated( incentive.etherReward, incentive.incentivizedLeverageRatio, incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapCooldownPeriod, incentive.incentivizedTwapMaxTradeSize ); } /** * OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress */ function withdrawEtherBalance() external onlyOperator noRebalanceInProgress { msg.sender.transfer(address(this).balance); } receive() external payable {} /* ============ External Getter Functions ============ */ /** * Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral * and borrow asset are retrieved from the Compound Price Oracle. * * return currentLeverageRatio Current leverage ratio in precise units (10e18) */ function getCurrentLeverageRatio() public view returns(uint256) { ActionInfo memory currentLeverageInfo = _createActionInfo(); return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue); } /** * Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is * below the etherReward, then return the balance of ETH instead. * * return etherReward Quantity of ETH reward in base units (10e18) */ function getCurrentEtherIncentive() external view returns(uint256) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) { // If ETH reward is below the balance on this contract, then return ETH balance on contract instead return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance; } else { return 0; } } /** * Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance() * 3 = call ripcord() * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalance() external view returns(ShouldRebalance) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio); } /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()3 = call ripcord() * * @param _customMinLeverageRatio Min leverage ratio passed in by caller * @param _customMaxLeverageRatio Max leverage ratio passed in by caller * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(ShouldRebalance) { require ( _customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio, "Custom bounds must be valid" ); uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio); } /** * Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types. */ function getStrategy() external view returns (ContractSettings memory) { return strategy; } function getMethodology() external view returns (MethodologySettings memory) { return methodology; } function getExecution() external view returns (ExecutionSettings memory) { return execution; } function getIncentive() external view returns (IncentiveSettings memory) { return incentive; } /* ============ Internal Functions ============ */ /** * Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on CompoundLeverageModule * */ function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action); uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance); bytes memory leverCallData = abi.encodeWithSignature( "lever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.borrowAsset, strategy.collateralAsset, borrowUnits, minReceiveCollateralUnits, execution.exchangeName, execution.leverExchangeData ); invokeManager(address(strategy.leverageModule), leverCallData); } /** * Calculate delever units Invoke delever on CompoundLeverageModule. */ function _delever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action); bytes memory deleverCallData = abi.encodeWithSignature( "delever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, collateralRebalanceUnits, minRepayUnits, execution.exchangeName, execution.deleverExchangeData ); invokeManager(address(strategy.leverageModule), deleverCallData); } /** * Invoke deleverToZeroBorrowBalance on CompoundLeverageModule. */ function _deleverToZeroBorrowBalance( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { // Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional .preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance)) .preciseDiv(_leverageInfo.action.setTotalSupply); bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature( "deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, maxCollateralRebalanceUnits, execution.exchangeName, execution.deleverExchangeData ); invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData); } /** * Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions * * return uint256 Calculated notional to trade * return uint256 Total notional to rebalance over TWAP */ function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) { uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false); _delever(_leverageInfo, chunkRebalanceNotional); } else { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true); _lever(_leverageInfo, chunkRebalanceNotional); } return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Create the leverage info struct to be used in internal functions * * return LeverageInfo Struct containing ActionInfo and other data */ function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) { ActionInfo memory actionInfo = _createActionInfo(); require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(actionInfo.borrowBalance > 0, "Borrow balance must exist"); // Get current leverage ratio uint256 currentLeverageRatio = _calculateCurrentLeverageRatio( actionInfo.collateralValue, actionInfo.borrowValue ); return LeverageInfo({ action: actionInfo, currentLeverageRatio: currentLeverageRatio, slippageTolerance: _slippageTolerance, twapMaxTradeSize: _maxTradeSize }); } /** * Create the action info struct to be used in internal functions * * return ActionInfo Struct containing data used by internal lever and delever functions */ function _createActionInfo() internal view returns(ActionInfo memory) { ActionInfo memory rebalanceInfo; // IMPORTANT: Compound oracle returns prices adjusted for decimals. USDC is 6 decimals so $1 * 10^18 * 10^18 / 10^6 = 10^30 rebalanceInfo.collateralPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetCollateralCToken)); rebalanceInfo.borrowPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetBorrowCToken)); // Calculate stored exchange rate which does not trigger a state update uint256 cTokenBalance = strategy.targetCollateralCToken.balanceOf(address(strategy.setToken)); rebalanceInfo.collateralBalance = cTokenBalance.preciseMul(strategy.targetCollateralCToken.exchangeRateStored()); rebalanceInfo.borrowBalance = strategy.targetBorrowCToken.borrowBalanceStored(address(strategy.setToken)); rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance); rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance); rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply(); return rebalanceInfo; } /** * Validate settings in constructor and setters when updating. */ function _validateSettings( MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) internal pure { require ( _methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0, "Must be valid min leverage" ); require ( _methodology.maxLeverageRatio >= _methodology.targetLeverageRatio, "Must be valid max leverage" ); require ( _methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0, "Must be valid recentering speed" ); require ( _execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(), "Unutilized leverage must be <100%" ); require ( _execution.slippageTolerance <= PreciseUnitMath.preciseUnit(), "Slippage tolerance must be <100%" ); require ( _incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(), "Incentivized slippage tolerance must be <100%" ); require ( _incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio, "Incentivized leverage ratio must be > max leverage ratio" ); require ( _methodology.rebalanceInterval >= _execution.twapCooldownPeriod, "Rebalance interval must be greater than TWAP cooldown period" ); require ( _execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod, "TWAP cooldown must be greater than incentivized TWAP cooldown" ); require ( _execution.twapMaxTradeSize <= _incentive.incentivizedTwapMaxTradeSize, "TWAP max trade size must be less than incentivized TWAP max trade size" ); } /** * Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used * in rebalance() and iterateRebalance() functions */ function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown) internal view { require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio"); require( block.timestamp.sub(lastTradeTimestamp) > _coolDown || _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio || _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio, "Cooldown not elapsed or not valid leverage ratio" ); } /** * Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord() */ function _validateRipcord(LeverageInfo memory _leverageInfo) internal view { require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio"); // If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed require(lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed"); } /** * Validate TWAP in the iterateRebalance() function */ function _validateTWAP() internal view { require(twapLeverageRatio > 0, "Not in TWAP state"); } /** * Validate not TWAP in the rebalance() function */ function _validateNonTWAP() internal view { require(twapLeverageRatio == 0, "Must call iterate"); } /** * Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under * the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance() */ function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) { return ( (twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio) || (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio) ); } /** * Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation * * return uint256 Current leverage ratio */ function _calculateCurrentLeverageRatio( uint256 _collateralValue, uint256 _borrowValue ) internal pure returns(uint256) { return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue)); } /** * Calculate the new leverage ratio using the flexible leverage methodology. The methodology reduces the size of each rebalance by weighting * the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower * the leverage token will move towards the target leverage each rebalance. * * return uint256 New leverage ratio based on the flexible leverage methodology */ function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) { // CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS)) // a: TLR * RS // b: (1- RS) * CLRt // c: (1- RS) * CLRt + TLR * RS // d: min(MAXLR, CLRt * (1 - RS) + TLR * RS) uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed); uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio); uint256 c = a.add(b); uint256 d = Math.min(c, methodology.maxLeverageRatio); return Math.max(methodology.minLeverageRatio, d); } /** * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units. * * return uint256 Chunked rebalance notional in collateral units * return uint256 Total rebalance notional in collateral units */ function _calculateChunkRebalanceNotional( LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio, bool _isLever ) internal view returns (uint256, uint256) { // Calculate absolute value of difference between new and current leverage ratio uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio); uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance); uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever); uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize); return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Calculate the max borrow / repay amount allowed in collateral units for lever / delever. This is due to overcollateralization requirements on * assets deposited in lending protocols for borrowing. * * For lever, max borrow is calculated as: * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals * * For delever, max borrow is calculated as: * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD * * Net borrow limit is calculated as: * The collateral value in USD * Compound collateral factor * (1 - unutilized leverage %) * * return uint256 Max borrow notional denominated in collateral asset */ function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) { // Retrieve collateral factor which is the % increase in borrow limit in precise units (75% = 75 * 1e16) ( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken)); uint256 netBorrowLimit = _actionInfo.collateralValue .preciseMul(collateralFactorMantissa) .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage)); if (_isLever) { return netBorrowLimit .sub(_actionInfo.borrowValue) .preciseDiv(_actionInfo.collateralPrice); } else { return _actionInfo.collateralBalance .preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue)) .preciseDiv(netBorrowLimit); } } /** * Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price. Compound oracle prices * already adjust for decimals in the token. * * return uint256 Position units to borrow */ function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice); } /** * Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * * return uint256 Min position units to receive after lever trade */ function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * and pair price (collateral oracle price / borrow oracle price). Compound oracle prices already adjust for decimals in the token. * * return uint256 Min position units to repay in borrow asset */ function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits .preciseMul(_actionInfo.collateralPrice) .preciseDiv(_actionInfo.borrowPrice) .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in * the engage() and rebalance() functions */ function _updateRebalanceState( uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, uint256 _newLeverageRatio ) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional < _totalRebalanceNotional) { twapLeverageRatio = _newLeverageRatio; } } /** * Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used * in iterateRebalance() */ function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal { lastTradeTimestamp = block.timestamp; // If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state. if (_chunkRebalanceNotional == _totalRebalanceNotional) { delete twapLeverageRatio; } } /** * Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function. */ function _updateRipcordState() internal { lastTradeTimestamp = block.timestamp; // If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the // incentivized threshold for ripcord. if (twapLeverageRatio > 0) { delete twapLeverageRatio; } } /** * Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required * incentive quantity, then transfer contract balance instead to prevent reverts. * * return uint256 Amount of ETH transferred to caller */ function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; } /** * Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { // If above ripcord threshold, then check if incentivized cooldown period has elapsed if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } } else { // If TWAP, then check if the cooldown period has elapsed if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } } else { // If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below // min leverage if ( block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } // If none of the above conditions are satisfied, then should not rebalance return ShouldRebalance.NONE; } } pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ICErc20 * * Interface for interacting with Compound cErc20 tokens (e.g. Dai, USDC) */ interface ICErc20 is IERC20 { function borrowBalanceCurrent(address _account) external returns (uint256); function borrowBalanceStored(address _account) external view returns (uint256); function balanceOfUnderlying(address _account) external returns (uint256); /** * Calculates the exchange rate from the underlying to the CToken * * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external view returns (address); /** * Sender supplies assets into the market and receives cTokens in exchange * * @notice Accrues interest whether or not the operation succeeds, unless reverted * @param _mintAmount The amount of the underlying asset to supply * @return uint256 0=success, otherwise a failure */ function mint(uint256 _mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemTokens The number of cTokens to redeem into underlying * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 _redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemAmount The amount of underlying to redeem * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 _redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param _borrowAmount The amount of the underlying asset to borrow * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 _borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @param _repayAmount The amount to repay * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 _repayAmount) external returns (uint256); } pragma solidity 0.6.10; /** * @title ICompoundPriceOracle * * Interface for interacting with Compound price oracle */ interface ICompoundPriceOracle { function getUnderlyingPrice(address _asset) external view returns(uint256); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; interface IFLIStrategyAdapter { function getStrategy() external view returns (FlexibleLeverageStrategyAdapter.ContractSettings memory); function getMethodology() external view returns (FlexibleLeverageStrategyAdapter.MethodologySettings memory); function getIncentive() external view returns (FlexibleLeverageStrategyAdapter.IncentiveSettings memory); function getExecution() external view returns (FlexibleLeverageStrategyAdapter.ExecutionSettings memory); function getCurrentLeverageRatio() external view returns (uint256); function shouldRebalance() external view returns (FlexibleLeverageStrategyAdapter.ShouldRebalance); function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FlexibleLeverageStrategyAdapter.ShouldRebalance); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IUniswapV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; /** * @title BaseAdapter * @author Set Protocol * * Abstract class that houses common adapter-related state and functions. */ abstract contract BaseAdapter { using AddressArrayUtils for address[]; /* ============ Events ============ */ event CallerStatusUpdated(address indexed _caller, bool _status); event AnyoneCallableUpdated(bool indexed _status); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == manager.operator(), "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; } /** * Throws if caller is a contract, can be used to stop flash loan and sandwich attacks */ modifier onlyEOA() { require(msg.sender == tx.origin, "Caller must be EOA Address"); _; } /** * Throws if not allowed caller */ modifier onlyAllowedCaller(address _caller) { require(isAllowedCaller(_caller), "Address not permitted to call"); _; } /* ============ State Variables ============ */ // Instance of manager contract IBaseManager public manager; // Boolean indicating if anyone can call function bool public anyoneCallable; // Mapping of addresses allowed to call function mapping(address => bool) public callAllowList; /* ============ Constructor ============ */ constructor(IBaseManager _manager) public { manager = _manager; } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions * * @param _callers Array of caller addresses to toggle status * @param _statuses Array of statuses for each caller */ function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator { require(_callers.length == _statuses.length, "Array length mismatch"); require(_callers.length > 0, "Array length must be > 0"); require(!_callers.hasDuplicate(), "Cannot duplicate callers"); for (uint256 i = 0; i < _callers.length; i++) { address caller = _callers[i]; bool status = _statuses[i]; callAllowList[caller] = status; emit CallerStatusUpdated(caller, status); } } /** * OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist * * @param _status Boolean indicating whether to allow anyone call */ function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); } /* ============ Internal Functions ============ */ /** * Invoke manager to transfer tokens from manager to other contract. * * @param _token Token being transferred from manager contract * @param _amount Amount of token being transferred */ function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount); invokeManager(_token, callData); } /** * Invoke call from manager * * @param _module Module to interact with * @param _encoded Encoded byte data */ function invokeManager(address _module, bytes memory _encoded) internal { manager.interactManager(_module, _encoded); } /** * Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved. * * return bool Boolean indicating if allowed caller */ function isAllowedCaller(address _caller) internal view virtual returns (bool) { return anyoneCallable || callAllowList[_caller]; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; } pragma solidity 0.6.10; /** * @title IComptroller * * Interface for interacting with Compound Comptroller */ interface IComptroller { /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256); function claimComp(address holder) external; function markets(address cTokenAddress) external view returns (bool, uint256, bool); } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface ICompoundLeverageModule { function sync( ISetToken _setToken ) external; function lever( ISetToken _setToken, address _borrowAsset, address _collateralAsset, uint256 _borrowQuantity, uint256 _minReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function delever( ISetToken _setToken, address _collateralAsset, address _repayAsset, uint256 _redeemQuantity, uint256 _minRepayQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function gulp( ISetToken _setToken, address _collateralAsset, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
Validate not TWAP in the rebalance() function/
function _validateNonTWAP() internal view { require(twapLeverageRatio == 0, "Must call iterate"); }
478,771
pragma solidity ^0.4.18; /** * Followine Token (WINE). More info www.followine.io */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Authorizable is Ownable { mapping(address => bool) public authorized; mapping(address => bool) public blocked; event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization); /** * @dev The Authorizable constructor sets the first `authorized` of the contract to the sender * account. */ constructor() public { authorized[msg.sender] = true; } /** * @dev Throws if called by any account other than the authorized. */ modifier onlyAuthorized() { require(authorized[msg.sender]); _; } /** * @dev Allows the current owner to set an authorization. * @param addressAuthorized The address to change authorization. */ function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public { emit AuthorizationSet(addressAuthorized, authorization); authorized[addressAuthorized] = authorization; } function setBlocked(address addressAuthorized, bool authorization) onlyOwner public { blocked[addressAuthorized] = authorization; } } contract Startable is Ownable, Authorizable { event Start(); event StopV(); bool public started = false; /** * @dev Modifier to make a function callable only when the contract is started. */ modifier whenStarted() { require( (started || authorized[msg.sender]) && !blocked[msg.sender] ); _; } /** * @dev called by the owner to start, go to normal state */ function start() onlyOwner public { started = true; emit Start(); } function stop() onlyOwner public { started = false; emit StopV(); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token from an address to another specified address * @param _sender The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFunction(address _sender, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_to != address(this)); require(_value <= balances[_sender]); // SafeMath.sub will throw if there is not enough balance. balances[_sender] = balances[_sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_sender, _to, _value); return true; } /** * @dev transfer token for a specified address (BasicToken transfer method) */ function transfer(address _to, uint256 _value) public returns (bool) { return transferFunction(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != address(this)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract StartToken is Startable, StandardToken { struct Pay{ uint256 date; uint256 value; uint256 category; } mapping( address => Pay[] ) log; mapping( address => uint256) transferredCoin; function addLog(address id, uint256 _x, uint256 _y, uint256 _z) internal { log[id].push(Pay(_x,_y,_z)); } function addTransferredCoin(address id, uint256 _x) private { transferredCoin[id] = transferredCoin[id] + _x; } function getFreeCoin(address field) private view returns (uint256){ uint arrayLength = log[field].length; uint256 totalValue = 0; for (uint i=0; i<arrayLength; i++) { uint256 date = log[field][i].date; uint256 value = log[field][i].value; uint256 category = log[field][i].category; // category = 1 acquisto private sale // category = 2 acquisto pre-ico // category = 3 acquisto ico // category = 4 acquisto bounty // category = 5 acquisto airdrop // category = 6 acquisto team // category = 7 acquisto advisor // category = 8 fondi bloccati per le aziende if( category == 1 || category == 2 ){ if( (date + 750 days) <= now ){ totalValue += value; }else if( (date + 510 days) <= now ){ totalValue += value.mul(60).div(100); }else if( (date + 390 days) <= now ){ totalValue += value.mul(30).div(100); } } if( category == 3 ){ if( (date + 690 days) <= now ){ totalValue += value; }else if( (date + 480 days) <= now ){ totalValue += value.mul(60).div(100); }else if( (date + 300 days) <= now ){ totalValue += value.mul(30).div(100); } } if( category == 4 || category == 5 ){ if( (date + 720 days) <= now ){ totalValue += value; }else if( (date + 540 days) <= now ){ totalValue += value.mul(75).div(100); }else if( (date + 360 days) <= now ){ totalValue += value.mul(50).div(100); } } if( category == 6 ){ if( (date + 1020 days) <= now ){ totalValue += value; }else if( (date + 810 days) <= now ){ totalValue += value.mul(70).div(100); }else if( (date + 630 days) <= now ){ totalValue += value.mul(40).div(100); }else if( (date + 450 days) <= now ){ totalValue += value.mul(20).div(100); } } if( category == 7 ){ if( (date + 810 days) <= now ){ totalValue += value; }else if( (date + 600 days) <= now ){ totalValue += value.mul(80).div(100); }else if( (date + 420 days) <= now ){ totalValue += value.mul(40).div(100); } } if( category == 8 ){ uint256 numOfMonths = now.sub(date).div(60).div(60).div(24).div(30).div(6); if( numOfMonths > 20 ){ numOfMonths = 20; } uint256 perc = 5; totalValue += value.mul((perc.mul(numOfMonths))).div(100); } if( category == 0 ){ totalValue += value; } } totalValue = totalValue - transferredCoin[field]; return totalValue; } function deleteCoin(address field,uint256 val) internal { uint arrayLength = log[field].length; for (uint i=0; i<arrayLength; i++) { uint256 value = log[field][i].value; if( value >= val ){ log[field][i].value = value - val; break; }else{ val = val - value; log[field][i].value = 0; } } } function getMyFreeCoin(address _addr) public constant returns(uint256) { return getFreeCoin(_addr); } function transfer(address _to, uint256 _value) public whenStarted returns (bool) { if( getFreeCoin(msg.sender) >= _value ){ if( super.transfer(_to, _value) ){ addLog(_to,now,_value,0); addTransferredCoin(msg.sender,_value); return true; }else{ return false; } } } function transferCustom(address _to, uint256 _value, uint256 _cat) onlyOwner whenStarted public returns(bool success) { addLog(_to,now,_value,_cat); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenStarted returns (bool) { if( getFreeCoin(_from) >= _value ){ if( super.transferFrom(_from, _to, _value) ){ addLog(_to,now,_value,0); addTransferredCoin(_from,_value); return true; }else{ return false; } } } function approve(address _spender, uint256 _value) public whenStarted returns (bool) { if( getFreeCoin(msg.sender) >= _value ){ return super.approve(_spender, _value); }else{ revert(); } } function increaseApproval(address _spender, uint _addedValue) public whenStarted returns (bool success) { if( getFreeCoin(msg.sender) >= allowed[msg.sender][_spender].add(_addedValue) ){ return super.increaseApproval(_spender, _addedValue); } } function decreaseApproval(address _spender, uint _subtractedValue) public whenStarted returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract HumanStandardToken is StandardToken, StartToken { /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { approve(_spender, _value); require(_spender.call(bytes4(keccak256("receiveApproval(address,uint256,bytes)")), msg.sender, _value, _extraData)); return true; } } contract BurnToken is StandardToken, StartToken { event Burn(address indexed burner, uint256 value); /** * @dev Function to burn tokens. * @param _burner The address of token holder. * @param _value The amount of token to be burned. */ function burnFunction(address _burner, uint256 _value) internal returns (bool) { require(_value > 0); require(_value <= balances[_burner]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_burner] = balances[_burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_burner, _value); if( _burner != tx.origin ){ deleteCoin(_burner,_value); } return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns(bool) { return burnFunction(msg.sender, _value); } /** * @dev Burns tokens from one address * @param _from address The address which you want to burn tokens from * @param _value uint256 the amount of tokens to be burned */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); // check if it has the budget allowed burnFunction(_from, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } } contract OriginToken is Authorizable, BasicToken, BurnToken { /** * @dev transfer token from tx.orgin to a specified address (onlyAuthorized contract) */ function originTransfer(address _to, uint256 _value) onlyAuthorized public returns (bool) { return transferFunction(tx.origin, _to, _value); } /** * @dev Burns a specific amount of tokens from tx.orgin. (onlyAuthorized contract) * @param _value The amount of token to be burned. */ function originBurn(uint256 _value) onlyAuthorized public returns(bool) { return burnFunction(tx.origin, _value); } } contract InterfaceProposal { uint256 public proposalNumber; string public proposal; bool public ongoingProposal; bool public investorWithdraw; mapping (uint256 => proposals) registry; event TapRaise(address,uint256,uint256,string); event CustomVote(address,uint256,uint256,string); event Destruct(address,uint256,uint256,string); struct proposals { address proposalSetter; uint256 votingStart; uint256 votingEnd; string proposalName; bool proposalResult; uint256 proposalType; } function _setRaiseProposal() internal; function _setCustomVote(string _custom, uint256 _tt) internal; function _setDestructProposal() internal; function _startProposal(string _proposal, uint256 _proposalType) internal; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract VoterInterface { uint256 public TotalAgreeVotes; uint256 public TotalDisagreeVotes; mapping (uint256 => mapping(address => bool)) VoteCast; function _Vote(bool _vote) internal; function _tallyVotes() internal returns (bool); } contract proposal is InterfaceProposal, BasicToken { using SafeMath for uint256; modifier noCurrentProposal { require(!ongoingProposal); require(balanceOf(msg.sender) >= 1000000); //1000 token _; } modifier currentProposal { require(ongoingProposal); require(registry[proposalNumber].votingEnd > block.timestamp); _; } // Proposal to raise Tap function _setRaiseProposal() internal noCurrentProposal { _startProposal("Raise",2); emit TapRaise(msg.sender, registry[proposalNumber].votingStart, registry[proposalNumber].votingEnd,"Vote To Raise Tap"); } function _setCustomVote(string _custom, uint256 _tt) internal noCurrentProposal { _startProposal(_custom,_tt); emit CustomVote(msg.sender, registry[proposalNumber].votingStart, registry[proposalNumber].votingEnd,_custom); } // Proposal to destroy the DAICO function _setDestructProposal() internal noCurrentProposal { _startProposal("Destruct",1); emit Destruct(msg.sender, registry[proposalNumber].votingStart, registry[proposalNumber].votingEnd,"Vote To destruct DAICO and return funds"); } function _startProposal(string _proposal, uint256 _proposalType) internal { ongoingProposal = true; proposalNumber = proposalNumber.add(1); registry[proposalNumber].votingStart = block.timestamp; registry[proposalNumber].proposalSetter = msg.sender; registry[proposalNumber].proposalName = _proposal; registry[proposalNumber].votingEnd = block.timestamp.add(1296000); registry[proposalNumber].proposalType = _proposalType; proposal = _proposal; } } contract Voter is VoterInterface , proposal { modifier alreadyVoted { require(!VoteCast[proposalNumber][msg.sender]); _; } function _Vote(bool _vote) internal alreadyVoted { VoteCast[proposalNumber][msg.sender] = true; if (_vote) { TotalAgreeVotes += 1; }else{ TotalDisagreeVotes += 1; } } function _tallyVotes() internal returns(bool) { if( TotalAgreeVotes > TotalDisagreeVotes ) { return true; }else{ return false; } } } contract FiatContract { function ETH(uint _id) public constant returns (uint256); function EUR(uint _id) public constant returns (uint256); function updatedAt(uint _id) public constant returns (uint); } contract WINE is StandardToken, StartToken, HumanStandardToken, BurnToken, OriginToken, Voter { using SafeMath for uint256; event Withdraw(uint256 amountWei, uint256 timestamp); struct refund { uint256 date; uint256 etherReceived; uint256 token; uint256 refunded; uint256 euro; } struct burnoutStruct { address add; uint256 date; string email; uint256 token; } uint8 public decimals = 3; string public name = "WineCoin"; string public symbol = "WINE"; uint256 public initialSupply; mapping (address => uint256) icoLog; mapping (address => refund[]) refundLog; burnoutStruct[] internal burnoutLog; uint256 internal firstSale = 5000000 * 10 ** uint(decimals); uint256 internal preICO = 10000000 * 10 ** uint(decimals); uint256 internal ICO = 120000000 * 10 ** uint(decimals); uint256 internal ICOFinal = 0; uint256 internal maxICOToken = 5000000 * 10 ** uint(decimals); uint256 internal firstSaleStart = 1543662000; uint256 internal firstSaleEnd = 1546300799; uint256 internal preICOStart = 1546300800; uint256 internal preICOEnd = 1548979199; uint256 internal ICOStep1 = 1548979200; uint256 internal ICOStep1E = 1549583999; uint256 internal ICOStep2 = 1549584000; uint256 internal ICOStep2E = 1550188799; uint256 internal ICOStep3 = 1550188800; uint256 internal ICOStep3E = 1550793599; uint256 internal ICOStep4 = 1550793600; uint256 internal ICOStep4E = 1551311999; uint256 internal ICOStepEnd = 1551312000; uint256 internal ICOEnd = 1553817599; uint256 internal tap = 192901234567901; // 500 ether al mese (wei/sec) uint256 internal tempTap = 0; uint256 internal constant secondWithdrawTime = 1567296000; uint256 internal lastWithdrawTime = secondWithdrawTime; uint256 internal firstWithdrawA = 0; address internal teamWallet = 0xb14F4c380BFF211222c18F026F3b1395F8e36F2F; uint256 internal softCap = 1000000; // un milione di euro uint256 internal hardCap = 12000000; // dodici milioni di euro uint256 internal withdrawPrice = 0; uint256 internal investorToken = 0; bool internal burnoutActive = false; mapping (address => uint256) investorLogToken; uint256 public totalEarned = 0; // totale ricevuto in euro uint256 public totalBitcoinReceived = 0; FiatContract internal price; modifier isValidTokenHolder { require(balanceOf(msg.sender) > 1000 * 10 ** uint(decimals)); //1000 token require(VoteCast[proposalNumber][msg.sender] == false); _; } constructor() public { totalSupply = 250000000 * 10 ** uint(decimals); initialSupply = totalSupply; balances[msg.sender] = totalSupply; price = FiatContract(0x8055d0504666e2B6942BeB8D6014c964658Ca591); } function TokenToSend(uint256 received, uint256 cost) internal returns (uint256) { uint256 ethCent = price.EUR(0); uint256 tokenToSendT = (received * 10 ** uint(decimals)).div(ethCent.mul(cost)); uint256 tokenToSendTC = received.div(ethCent.mul(cost)); require( tokenToSendTC.mul(cost).div(100) >= 90 ); require( totalEarned.add(tokenToSendTC.mul(cost).div(100)) <= hardCap ); totalEarned = totalEarned.add(tokenToSendTC.mul(cost).div(100)); return tokenToSendT; } function addLogRefund(address id, uint256 _x, uint256 _y, uint256 _z, uint256 _p) internal { refundLog[id].push(refund(_x,_y,_z,0,_p)); } function addLogBurnout(address id, uint256 _x, string _y, uint256 _z) internal { burnoutLog.push(burnoutStruct(id,_x,_y,_z)); } function() public payable { uint256 am = msg.value; if( now >= firstSaleStart && now <= firstSaleEnd ){ uint256 token = TokenToSend(am,3); if( token <= firstSale ){ addLog(msg.sender,now,token,1); transferFunction(owner,msg.sender, token); firstSale = firstSale.sub(token); investorToken = investorToken.add(token); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token); uint256 tm = token / 10 ** uint256(decimals); addLogRefund(msg.sender, now, am, token, tm.mul(3).div(100) ); }else{ revert(); } }else if( now >= preICOStart && now <= preICOEnd ){ uint256 token1 = TokenToSend(am,4); if( token1 <= preICO ){ addLog(msg.sender,now,token1,2); transferFunction(owner,msg.sender, token1); investorToken = investorToken.add(token1); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token1); preICO = preICO.sub(token1); addLogRefund(msg.sender, now, am, token1, (token1 / 10 ** uint(decimals)).mul(4).div(100)); }else{ revert(); } }else if( now >= ICOStep1 && now <= ICOStep1E ){ uint256 token2 = TokenToSend(am,5); if( ( icoLog[msg.sender].add(token2) ) <= maxICOToken && token2 <= ICO ){ icoLog[msg.sender] = icoLog[msg.sender].add(token2); addLog(msg.sender,now,token2,3); transferFunction(owner,msg.sender, token2); investorToken = investorToken.add(token2); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token2); ICO = ICO.sub(token2); addLogRefund(msg.sender, now, am, token2, (token2 / 10 ** uint(decimals)).mul(5).div(100)); }else{ revert(); } }else if( now >= ICOStep2 && now <= ICOStep2E ){ uint256 token3 = TokenToSend(am,6); if( ( icoLog[msg.sender].add(token3) ) <= maxICOToken && token3 <= ICO ){ icoLog[msg.sender] = icoLog[msg.sender].add(token3); addLog(msg.sender,now,token3,3); transferFunction(owner,msg.sender, token3); investorToken = investorToken.add(token3); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token3); ICO = ICO.sub(token3); addLogRefund(msg.sender, now, am, token3, (token3 / 10 ** uint(decimals)).mul(6).div(100)); }else{ revert(); } }else if( now >= ICOStep3 && now <= ICOStep3E ){ uint256 token4 = TokenToSend(am,7); if( ( icoLog[msg.sender].add(token4) ) <= maxICOToken && token4 <= ICO ){ icoLog[msg.sender] = icoLog[msg.sender].add(token4); addLog(msg.sender,now,token4,3); transferFunction(owner,msg.sender, token4); investorToken = investorToken.add(token4); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token4); ICO = ICO.sub(token4); addLogRefund(msg.sender, now, am, token4, (token4 / 10 ** uint(decimals)).mul(7).div(100)); }else{ revert(); } }else if( now >= ICOStep4 && now <= ICOStep4E ){ uint256 token5 = TokenToSend(am,8); if( ( icoLog[msg.sender].add(token5) ) <= maxICOToken && token5 <= ICO ){ icoLog[msg.sender] = icoLog[msg.sender].add(token5); addLog(msg.sender,now,token5,3); transferFunction(owner,msg.sender, token5); investorToken = investorToken.add(token5); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token5); ICO = ICO.sub(token5); addLogRefund(msg.sender, now, am, token5, (token5 / 10 ** uint(decimals)).mul(8).div(100)); }else{ revert(); } }else if( now >= ICOStepEnd && now <= ICOEnd ){ uint256 token6 = TokenToSend(am,10); if( ICOFinal <= 0 ){ ICOFinal = firstSale.add(preICO).add(ICO); firstSale = 0; preICO = 0; ICO = 0; } if( ( icoLog[msg.sender].add(token6) ) <= maxICOToken && token6 <= ICOFinal ){ icoLog[msg.sender] = icoLog[msg.sender].add(token6); addLog(msg.sender,now,token6,3); transferFunction(owner,msg.sender, token6); ICOFinal = ICOFinal.sub(token6); investorToken = investorToken.add(token6); investorLogToken[msg.sender] = investorLogToken[msg.sender].add(token6); addLogRefund(msg.sender, now, am, token6, (token6 / 10 ** uint(decimals)).mul(10).div(100)); }else{ revert(); } }else{ revert(); } } function firstWithdraw() public onlyOwner { require(!investorWithdraw); require(firstWithdrawA == 0); require(now >= ICOEnd); require(totalEarned >= softCap); uint256 softCapInEther = ((price.EUR(0)).mul(100)).mul(softCap); uint256 amount = softCapInEther.div(2); if( amount > address(this).balance ){ amount = address(this).balance; } firstWithdrawA = 1; teamWallet.transfer(amount); uint256 amBlocked = 62500000 * 10 ** uint(decimals); amBlocked = amBlocked.add(ICOFinal); ICOFinal = 0; addLog(teamWallet,now,amBlocked,8); transferFunction(owner,teamWallet,amBlocked); emit Withdraw(amount, now); } function calcTapAmount() internal view returns(uint256) { uint256 amount = now.sub(lastWithdrawTime).mul(tap); if(address(this).balance < amount) { amount = address(this).balance; } return amount; } function withdraw() public onlyOwner { require(!investorWithdraw); require(firstWithdrawA == 1); require(now >= secondWithdrawTime); uint256 amount = calcTapAmount(); lastWithdrawTime = now; teamWallet.transfer(amount); emit Withdraw(amount, now); } function _modTapProposal(uint256 _tap) public { require(now >= ICOEnd); TotalAgreeVotes = 0; TotalDisagreeVotes = 0; _setRaiseProposal(); tempTap = _tap; } function Armageddon() public { require(now >= ICOEnd); TotalAgreeVotes = 0; TotalDisagreeVotes = 0; _setDestructProposal(); } function _customProposal(string _proposal,uint256 _typeProposal) public onlyOwner { // impostare il _typeProposal a 3 per la funzione burnout, impostare a zero per le altre proposte require(now >= ICOEnd); TotalAgreeVotes = 0; TotalDisagreeVotes = 0; _setCustomVote(_proposal,_typeProposal); } function _ProposalVote(bool _vote) public currentProposal isValidTokenHolder { _Vote(_vote); } function _tallyingVotes() public { require(now > registry[proposalNumber].votingEnd); bool result = _tallyVotes(); registry[proposalNumber].proposalResult = result; _afterVoteAction(result); } function _afterVoteAction(bool result) internal { if(result && registry[proposalNumber].proposalType == 2 ) { tap = tempTap; tempTap = 0; ongoingProposal = false; }else if (result && registry[proposalNumber].proposalType == 1 ) { investorWithdraw = true; withdrawPrice = address(this).balance / investorToken; ongoingProposal = false; }else if (result && registry[proposalNumber].proposalType == 3 ) { burnoutActive = true; ongoingProposal = false; }else{ ongoingProposal = false; } } function burnout(string email) public { require(burnoutActive); uint256 val = balanceOf(msg.sender); burn(val); addLogBurnout(msg.sender, now, email, val); } function getBurnout(uint256 id) public onlyOwner constant returns (string __email, uint256 __val, address __add, uint256 __date) { return (burnoutLog[id].email, burnoutLog[id].token, burnoutLog[id].add, burnoutLog[id].date); } function refundEther(uint _amountP) public { require(balanceOf(msg.sender) >= _amountP); if( investorWithdraw == true ){ if( investorLogToken[msg.sender] >= _amountP ){ investorLogToken[msg.sender] = investorLogToken[msg.sender].sub(_amountP); burn(_amountP); uint256 revenue = _amountP * withdrawPrice; msg.sender.transfer(revenue); }else{ revert(); } }else{ uint256 refundable = 0; uint256 arrayLength = refundLog[msg.sender].length; for (uint256 e=0; e<arrayLength; e++){ if( now <= (refundLog[msg.sender][e].date).add(1296000) ){ if( refundLog[msg.sender][e].refunded == 0 ){ refundable = refundable.add(refundLog[msg.sender][e].token); } } } if( refundable >= _amountP ){ balances[owner] += _amountP; balances[msg.sender] -= _amountP; uint256 amountPrev = _amountP; for (uint256 i=0; i<arrayLength; i++){ if( now <= (refundLog[msg.sender][i].date).add(1296000) ){ if( refundLog[msg.sender][i].refunded == 0 ){ if( refundLog[msg.sender][i].token > amountPrev ){ uint256 ethTT = refundLog[msg.sender][i].token / 10 ** uint(decimals); uint256 ethT = (refundLog[msg.sender][i].etherReceived).div(ethTT * 10 ** uint(decimals)); msg.sender.transfer(ethT.mul(amountPrev).sub(1 wei)); refundLog[msg.sender][i].etherReceived = (refundLog[msg.sender][i].etherReceived).sub(ethT.mul(amountPrev).sub(1 wei)); refundLog[msg.sender][i].token = (refundLog[msg.sender][i].token).sub(amountPrev); investorLogToken[msg.sender] = investorLogToken[msg.sender].sub(amountPrev); amountPrev = 0; break; }else{ msg.sender.transfer(refundLog[msg.sender][i].etherReceived); refundLog[msg.sender][i].refunded = 1; amountPrev = amountPrev.sub(refundLog[msg.sender][i].token); totalEarned = totalEarned.sub(refundLog[msg.sender][i].euro); investorLogToken[msg.sender] = investorLogToken[msg.sender].sub(amountPrev); } } } } emit Transfer(msg.sender, this, _amountP); }else{ revert(); } } } function addBitcoin(uint256 btc, uint256 eur) public onlyOwner { totalBitcoinReceived = totalBitcoinReceived.add(btc); totalEarned = totalEarned.add(eur); } function removeBitcoin(uint256 btc, uint256 eur) public onlyOwner { totalBitcoinReceived = totalBitcoinReceived.sub(btc); totalEarned = totalEarned.sub(eur); } function historyOfProposal(uint256 _id) public constant returns (string _name, bool _result) { return (registry[_id].proposalName, registry[_id].proposalResult); } }
Burns a specific amount of tokens. _value The amount of token to be burned./
function burn(uint256 _value) public returns(bool) { return burnFunction(msg.sender, _value); }
968,104
pragma solidity ^0.5.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract GetLuckyFinance is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; address rewardsWallet = 0xf7db36F723180058eE1a19dFE07a9c4Eb8bCc4b5; address deployerWallet = 0xf7db36F723180058eE1a19dFE07a9c4Eb8bCc4b5; string constant tokenName = "GetLucky"; string constant tokenSymbol = "GLUCKY"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 168 * (10 ** 18); uint256 public basePercent = 168; uint256 public taxPercent = 832; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function getPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 fivePercent = roundValue.mul(basePercent).div(10000); return fivePercent; } function getRewardsPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(taxPercent); uint256 rewardsPercent = roundValue.mul(taxPercent).div(10000); return rewardsPercent; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); if (msg.sender == deployerWallet) { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } else { uint256 tokensToBurn = getPercent(value); uint256 tokensForRewards = getRewardsPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn).sub(tokensForRewards); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[rewardsWallet] = _balances[rewardsWallet].add(tokensForRewards); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, value); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, rewardsWallet, tokensForRewards); emit Transfer(msg.sender, address(0), tokensToBurn); } return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); if (from == deployerWallet) { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } else { uint256 tokensToBurn = getPercent(value); uint256 tokensForRewards = getRewardsPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn).sub(tokensForRewards); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[rewardsWallet] = _balances[rewardsWallet].add(tokensForRewards); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(from, to, value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, rewardsWallet, tokensForRewards); emit Transfer(from, address(0), tokensToBurn); } return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } // Internal Mint Function Only function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
Internal Mint Function Only
function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
1,556,873
pragma solidity ^0.5.4; library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /* * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply = 1e6; constructor() public { _balances[msg.sender] = 1e6; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract OathForge is ERC721, ERC721Metadata, Ownable { using SafeMath for uint256; uint256 private _totalSupply; uint256 private _nextTokenId; mapping(uint256 => uint256) private _sunsetInitiatedAt; mapping(uint256 => uint256) private _sunsetLength; mapping(uint256 => uint256) private _redemptionCodeHashSubmittedAt; mapping(uint256 => bytes32) private _redemptionCodeHash; mapping(address => bool) private _isBlacklisted; /// @param name The ERC721 Metadata name /// @param symbol The ERC721 Metadata symbol constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} /// @dev Emits when a sunset has been initiated /// @param tokenId The token id event SunsetInitiated(uint256 indexed tokenId); /// @dev Emits when a redemption code hash has been submitted /// @param tokenId The token id /// @param redemptionCodeHash The redemption code hash event RedemptionCodeHashSubmitted(uint256 indexed tokenId, bytes32 redemptionCodeHash); /// @dev Returns the total number of tokens (minted - burned) registered function totalSupply() external view returns(uint256){ return _totalSupply; } /// @dev Returns the token id of the next minted token function nextTokenId() external view returns(uint256){ return _nextTokenId; } /// @dev Returns if an address is blacklisted /// @param to The address to check function isBlacklisted(address to) external view returns(bool){ return _isBlacklisted[to]; } /// @dev Returns the timestamp at which a token's sunset was initated. Returns 0 if no sunset has been initated. /// @param tokenId The token id function sunsetInitiatedAt(uint256 tokenId) external view returns(uint256){ return _sunsetInitiatedAt[tokenId]; } /// @dev Returns the sunset length of a token /// @param tokenId The token id function sunsetLength(uint256 tokenId) external view returns(uint256){ return _sunsetLength[tokenId]; } /// @dev Returns the redemption code hash submitted for a token /// @param tokenId The token id function redemptionCodeHash(uint256 tokenId) external view returns(bytes32){ return _redemptionCodeHash[tokenId]; } /// @dev Returns the timestamp at which a redemption code hash was submitted /// @param tokenId The token id function redemptionCodeHashSubmittedAt(uint256 tokenId) external view returns(uint256){ return _redemptionCodeHashSubmittedAt[tokenId]; } /// @dev Mint a token. Only `owner` may call this function. /// @param to The receiver of the token /// @param tokenURI The tokenURI of the the tokenURI /// @param __sunsetLength The length (in seconds) that a sunset period can last function mint(address to, string memory tokenURI, uint256 __sunsetLength) public onlyOwner { _mint(to, _nextTokenId); _sunsetLength[_nextTokenId] = __sunsetLength; _setTokenURI(_nextTokenId, tokenURI); _nextTokenId = _nextTokenId.add(1); _totalSupply = _totalSupply.add(1); } /// @dev Initiate a sunset. Sets `sunsetInitiatedAt` to current timestamp. Only `owner` may call this function. /// @param tokenId The id of the token function initiateSunset(uint256 tokenId) external onlyOwner { require(tokenId < _nextTokenId); require(_sunsetInitiatedAt[tokenId] == 0); _sunsetInitiatedAt[tokenId] = now; emit SunsetInitiated(tokenId); } /// @dev Submit a redemption code hash for a specific token. Burns the token. Sets `redemptionCodeHashSubmittedAt` to current timestamp. Decreases `totalSupply` by 1. /// @param tokenId The id of the token /// @param __redemptionCodeHash The redemption code hash function submitRedemptionCodeHash(uint256 tokenId, bytes32 __redemptionCodeHash) external { _burn(msg.sender, tokenId); _redemptionCodeHashSubmittedAt[tokenId] = now; _redemptionCodeHash[tokenId] = __redemptionCodeHash; _totalSupply = _totalSupply.sub(1); emit RedemptionCodeHashSubmitted(tokenId, __redemptionCodeHash); } /// @dev Transfers the ownership of a given token ID to another address. Usage of this method is discouraged, use `safeTransferFrom` whenever possible. Requires the msg sender to be the owner, approved, or operator /// @param from current owner of the token /// @param to address to receive the ownership of the given token ID /// @param tokenId uint256 ID of the token to be transferred function transferFrom(address from, address to, uint256 tokenId) public { require(!_isBlacklisted[to]); if (_sunsetInitiatedAt[tokenId] > 0) { require(now <= _sunsetInitiatedAt[tokenId].add(_sunsetLength[tokenId])); } super.transferFrom(from, to, tokenId); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { require(!_isBlacklisted[to]); super.approve(to, tokenId); } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(!_isBlacklisted[to]); super.setApprovalForAll(to, approved); } /// @dev Set `tokenUri`. Only `owner` may do this. /// @param tokenId The id of the token /// @param tokenURI The token URI function setTokenURI(uint256 tokenId, string calldata tokenURI) external onlyOwner { _setTokenURI(tokenId, tokenURI); } /// @dev Set if an address is blacklisted /// @param to The address to change /// @param __isBlacklisted True if the address should be blacklisted, false otherwise function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner { _isBlacklisted[to] = __isBlacklisted; } } contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract RiftPact is ERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; uint256 private _parentTokenId; uint256 private _auctionAllowedAt; address private _currencyAddress; address private _parentToken; uint256 private _minAuctionCompleteWait; uint256 private _minBidDeltaPermille; uint256 private _auctionStartedAt; uint256 private _auctionCompletedAt; uint256 private _minBid = 1; uint256 private _topBid; address private _topBidder; uint256 private _topBidSubmittedAt; mapping(address => bool) private _isBlacklisted; /// @param __parentToken The address of the OathForge contract /// @param __parentTokenId The id of the token on the OathForge contract /// @param __totalSupply The total supply /// @param __currencyAddress The address of the currency contract /// @param __auctionAllowedAt The timestamp at which anyone can start an auction /// @param __minAuctionCompleteWait The minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed /// @param __minBidDeltaPermille The minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be constructor( address __parentToken, uint256 __parentTokenId, uint256 __totalSupply, address __currencyAddress, uint256 __auctionAllowedAt, uint256 __minAuctionCompleteWait, uint256 __minBidDeltaPermille ) public { _parentToken = __parentToken; _parentTokenId = __parentTokenId; _currencyAddress = __currencyAddress; _auctionAllowedAt = __auctionAllowedAt; _minAuctionCompleteWait = __minAuctionCompleteWait; _minBidDeltaPermille = __minBidDeltaPermille; _mint(msg.sender, __totalSupply); } /// @dev Emits when an auction is started event AuctionStarted(); /// @dev Emits when the auction is completed /// @param bid The final bid price of the auction /// @param winner The winner of the auction event AuctionCompleted(address winner, uint256 bid); /// @dev Emits when there is a bid /// @param bid The bid /// @param bidder The address of the bidder event Bid(address bidder, uint256 bid); /// @dev Emits when there is a payout /// @param to The address of the account paying out /// @param balance The balance of `to` prior to the paying out event Payout(address to, uint256 balance); /// @dev Returns the OathForge contract address. **UI should check for phishing.**. function parentToken() external view returns(address) { return _parentToken; } /// @dev Returns the OathForge token id. **Does not imply RiftPact has ownership over token.** function parentTokenId() external view returns(uint256) { return _parentTokenId; } /// @dev Returns the currency contract address. function currencyAddress() external view returns(address) { return _currencyAddress; } /// @dev Returns the minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed. function minAuctionCompleteWait() external view returns(uint256) { return _minAuctionCompleteWait; } /// @dev Returns the minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be function minBidDeltaPermille() external view returns(uint256) { return _minBidDeltaPermille; } /// @dev Returns the timestamp at which anyone can start an auction by calling [`startAuction()`](#startAuction()) function auctionAllowedAt() external view returns(uint256) { return _auctionAllowedAt; } /// @dev Returns the minimum bid in currency function minBid() external view returns(uint256) { return _minBid; } /// @dev Returns the timestamp at which an auction was started or 0 if no auction has been started function auctionStartedAt() external view returns(uint256) { return _auctionStartedAt; } /// @dev Returns the timestamp at which an auction was completed or 0 if no auction has been completed function auctionCompletedAt() external view returns(uint256) { return _auctionCompletedAt; } /// @dev Returns the top bid or 0 if no bids have been placed function topBid() external view returns(uint256) { return _topBid; } /// @dev Returns the top bidder or `address(0)` if no bids have been placed function topBidder() external view returns(address) { return _topBidder; } /// @dev Start an auction function startAuction() external nonReentrant { require(_auctionStartedAt == 0); require( (now >= _auctionAllowedAt) || (OathForge(_parentToken).sunsetInitiatedAt(_parentTokenId) > 0) ); emit AuctionStarted(); _auctionStartedAt = now; } /// @dev Submit a bid. Must have sufficient funds approved in currency contract (bid * totalSupply). /// @param bid Bid in currency function submitBid(uint256 bid) external nonReentrant { require(_auctionStartedAt > 0); require(_auctionCompletedAt == 0); require(bid >= _minBid); emit Bid(msg.sender, bid); uint256 _totalSupply = totalSupply(); if (_topBidder != address(0)) { /// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid /* require(ERC20(_currencyAddress).transfer(_topBidder, _topBid * _totalSupply)); */ require(ERC20(_currencyAddress).transfer(_topBidder, _topBid)); } /// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid /* require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid * _totalSupply)); */ require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid)); _topBid = bid; _topBidder = msg.sender; _topBidSubmittedAt = now; /* 3030 * 10 = 30300 delta = 30300 / 1000 = 30,3 30300 % 1000 = 300 > 0, yes roundUp = 1 minBid = 3030 + 30 + 1 which is wrong, it should be 3060 instead of 3061 */ uint256 minBidNumerator = bid * _minBidDeltaPermille; uint256 minBidDelta = minBidNumerator / 1000; uint256 minBidRoundUp = 0; /// NOTE commented out because it doesn't work as expected with big bids /* if((bid * _minBidDeltaPermille) % 1000 > 0) { minBidRoundUp = 1; } */ if((bid * _minBidDeltaPermille) < 1000) { minBidRoundUp = 1; } _minBid = bid + minBidDelta + minBidRoundUp; } /// @dev Complete auction function completeAuction() external { require(_auctionCompletedAt == 0); require(_topBid > 0); require((_topBidSubmittedAt + _minAuctionCompleteWait) < now); emit AuctionCompleted(_topBidder, _topBid); _auctionCompletedAt = now; } /// @dev Payout `currency` after auction completed function payout() external nonReentrant { uint256 balance = balanceOf(msg.sender); require(balance > 0); require(_auctionCompletedAt > 0); emit Payout(msg.sender, balance); /// NOTE this won't work since we can't send more tokens than what's already in this contract /* require(ERC20(_currencyAddress).transfer(msg.sender, balance * _topBid)); */ require(ERC20(_currencyAddress).transfer(msg.sender, _topBid)); /// NOTE Remove this since the sender doesn't have any riftPact tokens inside this contract so we can't burn them. /* _burn(msg.sender, balance); */ } /// @dev Returns if an address is blacklisted /// @param to The address to check function isBlacklisted(address to) external view returns(bool){ return _isBlacklisted[to]; } /// @dev Set if an address is blacklisted /// @param to The address to change /// @param __isBlacklisted True if the address should be blacklisted, false otherwise function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner { _isBlacklisted[to] = __isBlacklisted; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { require(!_isBlacklisted[to]); return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(!_isBlacklisted[to]); return super.transferFrom(from, to, value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { if (value > 0) { require(!_isBlacklisted[spender]); } return super.approve(spender, value); } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(!_isBlacklisted[spender]); return super.increaseAllowance(spender, addedValue); } }
Set `tokenUri`. Only `owner` may do this. tokenId The id of the token tokenURI The token URI
function setTokenURI(uint256 tokenId, string calldata tokenURI) external onlyOwner { _setTokenURI(tokenId, tokenURI); }
5,390,910
./full_match/1/0x910DdC5A26285e53c10927D0723581A990e0ebFC/sources/contracts/MoonLabsTokenLocker.sol
Split a current lock into two separate locks amount determined by the sender. If not whitelisted, fees are in eth. This function supports both linear and standard locks. to address of split receiver _nonce ID of desired lock instance amount number of tokens sent to new lock/ Check if token is whitelisted
function splitLockETH( address to, address withdrawalAddress, uint64 _nonce, uint amount ) external payable { uint currentAmount = lockInstance[_nonce].currentAmount; uint depositAmount = lockInstance[_nonce].depositAmount; address tokenAddress = lockInstance[_nonce].tokenAddress; if (whitelistContract.getIsWhitelisted(tokenAddress, false)) { require(msg.value == 0, "Incorrect Price"); require(msg.value == ethSplitPrice, "Incorrect Price"); _splitLock( _nonce, depositAmount, currentAmount, amount, tokenAddress, withdrawalAddress, to ); }
8,334,959
// File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/Rainbows.sol pragma solidity ^0.8.0; interface InterfaceNoundles { function noundleBalance(address owner) external view returns(uint256); } interface InterfaceEvilNoundles { function companionBalance(address owner) external view returns(uint256); function getEvilNoundleOwners() external view returns (address[] memory); function lowLandBalance(address owner) external view returns(uint256); function midLandBalance(address owner) external view returns(uint256); function highLandBalance(address owner) external view returns(uint256); } interface InterfaceOriginalRainbows { function balanceOf(address owner) external view returns(uint256); function burn(address user, uint256 amount) external; function claimReward() external; } contract Rainbows is ERC20, Ownable, Pausable { InterfaceNoundles public Noundles; InterfaceEvilNoundles public EvilNoundles; InterfaceOriginalRainbows public OriginalRainbows; // If we are pulling value from the old contract also. bool public UseOriginalRainbowsBalance = true; // The starting block. uint256 public startBlock; uint256 public startBlockCompanion; // The maximum that can ever be minted. uint256 public maximumSupply = 33333333 ether; // Noundle holders: The interval that the user is paid out. uint256 public interval = 86400; uint256 public rate = 4 ether; uint256 public companionInterval = 86400; uint256 public companionRate = 2 ether; // Land protection uint256 public landPertectionRateLow = 2; uint256 public landPertectionRateMid = 5; uint256 public landPertectionRateHigh = 10; // Steal Amount. bool public stealingEnabled = false; uint256 public stealPercentage = 20; // Loss on a trade. uint256 public tradeLoss = 35; bool public collectTransferRewards = false; // The rewards for the user (OG). mapping(address => uint256) public rewards; mapping(address => uint256) public companionRewards; mapping(address => uint256) public evilRewards; // The last time they were paid out. mapping(address => uint256) public lastUpdate; mapping(address => uint256) public lastUpdateCompanion; // Extended access mapping(address => bool) public extendedAccess; // Only allow the contract to interact with it. modifier onlyFromNoundles() { require((msg.sender == address(Noundles)), "Your address doesn't have permissing"); _; } modifier onlyFromEvilNoundles() { require(msg.sender == address(EvilNoundles)); _; } modifier onlyFromRestricted() { require(extendedAccess[msg.sender], "Your address does not have permission to use."); _; } constructor(address noundlesAddress, address evilNoundlesAddress, address ogRainbowsAddress) ERC20("NoundlesRainbows", "Rainbows") { // Set the address to interfaces. Noundles = InterfaceNoundles(noundlesAddress); EvilNoundles = InterfaceEvilNoundles(evilNoundlesAddress); OriginalRainbows = InterfaceOriginalRainbows(ogRainbowsAddress); // Set the starting block. startBlock = block.timestamp; startBlockCompanion = block.timestamp; // Pause the system so no one can interact with it. _pause(); } /* Admin Utility. */ // Pause it. function pause() public onlyOwner { _pause(); } // Unpause it. function unpause() public onlyOwner { _unpause(); } // Set the start block. function setStartBlock(uint256 arg) public onlyOwner { if(arg == 0){ startBlock = block.timestamp; }else{ startBlock = arg; } } // Set the start block for companions. function setStartBlockCompanion(uint256 arg) public onlyOwner { if(arg == 0){ startBlockCompanion = block.timestamp; }else{ startBlockCompanion = arg; } } // Set the status of stealing. function setStealingStatus(bool arg) public onlyOwner { stealingEnabled = arg; } function setCollectTransferRewards(bool arg) public onlyOwner { collectTransferRewards = arg; } // Set the status of the rainbows balance. function setUseOriginalRainbowBalance(bool arg) public onlyOwner { UseOriginalRainbowsBalance = arg; } // Set the start block. function setIntervalAndRate(uint256 _interval, uint256 _rate) public onlyOwner { interval = _interval; rate = _rate; } // Set the steal rate. function setStealPercentage(uint256 _arg) public onlyOwner { stealPercentage = _arg; } // Set the trade loss. function setLossPercentage(uint256 _arg) public onlyOwner { tradeLoss = _arg; } // Set the land protection rate. function setLandProtectionRates(uint256 _low, uint256 _mid, uint256 _high) public onlyOwner { landPertectionRateLow = _low; landPertectionRateMid = _mid; landPertectionRateHigh = _high; } // Set the start block. function setCompanionIntervalAndRate(uint256 _interval, uint256 _rate) public onlyOwner { companionInterval = _interval; companionRate = _rate; } // Set the address for the contract. function setNoundlesContractAddress(address _noundles) public onlyOwner { Noundles = InterfaceNoundles(_noundles); } // Set the address for the evil noundles contract. function setEvilNoundlesContractAddress(address _noundles) public onlyOwner { EvilNoundles = InterfaceEvilNoundles(_noundles); } // Set the address for the original rainbow contract. function setOGRainbowsContractAddress(address _noundles) public onlyOwner { OriginalRainbows = InterfaceOriginalRainbows(_noundles); } // Set the address for the contract. function setAddressAccess(address _noundles, bool _value) public onlyOwner { extendedAccess[_noundles] = _value; } // Get the access status for a address. function getAddressAccess(address user) external view returns(bool) { return extendedAccess[user]; } // Burn the tokens required to evolve. function burnMultiple(address [] memory users, uint256 [] memory amount) external onlyFromRestricted { for(uint256 i = 0; i < users.length; i += 1){ _burn(users[i], amount[i]); } } // Burn the tokens required to evolve. function burn(address user, uint256 amount) external onlyFromRestricted { _burn(user, amount); } // Mint some tokens for uniswap. function adminCreate(address [] memory users, uint256 [] memory amount) public onlyOwner { for(uint256 i = 0; i < users.length; i += 1){ _mint(users[i], amount[i]); } } /* Helpers. */ // The rewards to the user. function getOGRainbowsClaimable(address user) external view returns(uint256) { // Always 0 if it's not setup. if(UseOriginalRainbowsBalance == false || address(OriginalRainbows) == address(0)){ return 0; } return OriginalRainbows.balanceOf(user); } // The rewards to the user. function getTotalClaimable(address user) external view returns(uint256) { return rewards[user] + getPendingOGReward(user); } // The rewards to the user. function getTotalCompanionClaimable(address user) external view returns(uint256) { return companionRewards[user] + getPendingCompanionReward(user); } function getTotalStolenClaimable(address user) external view returns(uint256) { return evilRewards[user]; } // The rewards to the user. function getLastUpdate(address user) external view returns(uint256) { return lastUpdate[user]; } // The rewards to the user. function getLastUpdateCompanion(address user) external view returns(uint256) { return lastUpdateCompanion[user]; } // Set the address for the contract. function setLastUpdate(address[] memory _noundles, uint256 [] memory values) public onlyOwner { for(uint256 i = 0; i < _noundles.length; i += 1){ lastUpdate[_noundles[i]] = values[i]; } } // Set the address for the contract. function setLastUpdateCompanion(address[] memory _noundles, uint256 [] memory values) public onlyOwner { for(uint256 i = 0; i < _noundles.length; i += 1){ lastUpdateCompanion[_noundles[i]] = values[i]; } } // Update the supply. function setMaximumSupply(uint256 _arg) public onlyOwner { maximumSupply = _arg; } /* User Utilities. */ // Transfer the tokens (only accessable from the contract). function transferTokens(address _from, address _to) onlyFromRestricted external { if(collectTransferRewards){ if(_from != address(0)){ rewards[_from] += (getPendingOGReward(_from) * (100 - tradeLoss)) / 100; companionRewards[_from] += (getPendingCompanionReward(_from) * (100 - tradeLoss)) / 100; lastUpdate[_from] = block.timestamp; lastUpdateCompanion[_from] = block.timestamp; } if(_to != address(0)){ rewards[_to] += getPendingOGReward(_to); companionRewards[_to] += getPendingCompanionReward(_to); lastUpdate[_to] = block.timestamp; lastUpdateCompanion[_to] = block.timestamp; } } } // Pay out the holder. function claimReward() external whenNotPaused { // Make a local copy of the rewards. uint256 _ogRewards = rewards[msg.sender]; uint256 _compRewards = companionRewards[msg.sender]; uint256 _evilRewards = evilRewards[msg.sender]; // Automatically claim the old rainbows. if(UseOriginalRainbowsBalance){ OriginalRainbows.claimReward(); } // Get the rewards. uint256 pendingOGRewards = getPendingOGReward(msg.sender); uint256 pendingCompanionRewards = getPendingCompanionReward(msg.sender); uint256 pendingOGRainbows = getOGRainbowsPending(msg.sender); // Reset the rewards. rewards[msg.sender] = 0; companionRewards[msg.sender] = 0; evilRewards[msg.sender] = 0; // Reset the block. lastUpdate[msg.sender] = block.timestamp; lastUpdateCompanion[msg.sender] = block.timestamp; // Add up the totals. uint256 totalRewardsWithoutEvil = _ogRewards + _compRewards + pendingOGRewards + pendingCompanionRewards; // Block if we hit our limit. require(totalSupply() + totalRewardsWithoutEvil < maximumSupply, "No longer able to mint tokens."); // How much is one percent worth. uint256 percent = totalRewardsWithoutEvil / 100; // The calculated steal percentage. uint256 calculatedStealPercentage = stealPercentage; // If stealing is enabled. if(stealingEnabled){ uint256 landProtection = 0; // Calculate how much the land protected. if(EvilNoundles.highLandBalance(msg.sender) > 0){ landProtection = landPertectionRateHigh; }else if(EvilNoundles.midLandBalance(msg.sender) > 0){ landProtection = landPertectionRateMid; }else if(EvilNoundles.lowLandBalance(msg.sender) > 0){ landProtection = landPertectionRateLow; } if(landProtection < calculatedStealPercentage){ calculatedStealPercentage -= landProtection; }else{ calculatedStealPercentage = 0; } // Handle stealing. address[] memory evilNoundleLists = EvilNoundles.getEvilNoundleOwners(); // Cut the total amount stolen into shares for each noundle. uint256 rewardPerEvilNoundle = (percent * calculatedStealPercentage) / evilNoundleLists.length; // Give each evil noundle holder a cut into their stolen. for(uint256 _index; _index < evilNoundleLists.length; _index += 1){ evilRewards[evilNoundleLists[_index]] += rewardPerEvilNoundle; } }else{ // If stealing isn't enabled, set it to 0. calculatedStealPercentage = 0; } // The final result after it was stolen from by those evil noundles :( uint256 totalRewards = (percent * (100 - calculatedStealPercentage)) + _evilRewards + pendingOGRainbows; // Before we claim, if we have any pendingOG then burn them. if(pendingOGRainbows > 0){ OriginalRainbows.burn(msg.sender, pendingOGRainbows); } // Mint the user their tokens. _mint(msg.sender, totalRewards); } // Get the total rewards. function getPendingOGReward(address user) internal view returns(uint256) { return Noundles.noundleBalance(user) * rate * (block.timestamp - (lastUpdate[user] >= startBlock ? lastUpdate[user] : startBlock)) / interval; } // Get the total rewards. function getPendingCompanionReward(address user) internal view returns(uint256) { return EvilNoundles.companionBalance(user) * companionRate * (block.timestamp - (lastUpdateCompanion[user] >= startBlockCompanion ? lastUpdateCompanion[user] : startBlockCompanion)) / companionInterval; } function getOGRainbowsPending(address user) internal view returns(uint256) { // Always 0 if it's not setup. if(UseOriginalRainbowsBalance == false || address(OriginalRainbows) == address(0)){ return 0; } return OriginalRainbows.balanceOf(user); } }
Set the start block.
function setStartBlock(uint256 arg) public onlyOwner { if(arg == 0){ startBlock = block.timestamp; startBlock = arg; } }
170,166
pragma solidity ^0.4.13; contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return capReached || super.hasEnded(); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return withinCap && super.validPurchase(); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract FinalizableCappedCrowdsale is CappedCrowdsale, Ownable { bool public isFinalized = false; bool public reconciliationDateSet = false; uint public reconciliationDate = 0; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwnerOrAfterReconciliation public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function setReconciliationDate(uint _reconciliationDate) onlyOwner { reconciliationDate = _reconciliationDate; reconciliationDateSet = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } modifier onlyOwnerOrAfterReconciliation(){ require(msg.sender == owner || (reconciliationDate <= now && reconciliationDateSet)); _; } } contract PoolSegregationCrowdsale is Ownable { /** * we include the crowdsale eventhough this is not treated in this contract (zeppelin's CappedCrowdsale ) */ enum POOLS {POOL_STRATEGIC_INVESTORS, POOL_COMPANY_RESERVE, POOL_USER_ADOPTION, POOL_TEAM, POOL_ADVISORS, POOL_PROMO} using SafeMath for uint; mapping (uint => PoolInfo) poolMap; struct PoolInfo { uint contribution; uint poolCap; } function PoolSegregationCrowdsale(uint _cap) { poolMap[uint(POOLS.POOL_STRATEGIC_INVESTORS)] = PoolInfo(0, _cap.mul(285).div(1000)); poolMap[uint(POOLS.POOL_COMPANY_RESERVE)] = PoolInfo(0, _cap.mul(10).div(100)); poolMap[uint(POOLS.POOL_USER_ADOPTION)] = PoolInfo(0, _cap.mul(20).div(100)); poolMap[uint(POOLS.POOL_TEAM)] = PoolInfo(0, _cap.mul(3).div(100)); poolMap[uint(POOLS.POOL_ADVISORS)] = PoolInfo(0, _cap.mul(3).div(100)); poolMap[uint(POOLS.POOL_PROMO)] = PoolInfo(0, _cap.mul(3).div(100)); } modifier onlyIfInPool(uint amount, uint poolId) { PoolInfo poolInfo = poolMap[poolId]; require(poolInfo.contribution.add(amount) <= poolInfo.poolCap); _; poolInfo.contribution = poolInfo.contribution.add(amount); } function transferRemainingTokensToUserAdoptionPool(uint difference) internal { poolMap[uint(POOLS.POOL_USER_ADOPTION)].poolCap = poolMap[uint(POOLS.POOL_USER_ADOPTION)].poolCap.add(difference); } function getPoolCapSize(uint poolId) public view returns(uint) { return poolMap[poolId].poolCap; } } contract LuckCashCrowdsale is FinalizableCappedCrowdsale, PoolSegregationCrowdsale { // whitelist registry contract WhiteListRegistry public whitelistRegistry; using SafeMath for uint; uint constant public CAP = 600000000*1e18; mapping (address => uint) contributions; /** * event for token vest fund launch * @param beneficiary who will get the tokens once they are vested * @param fund vest fund that will received the tokens * @param tokenAmount amount of tokens purchased */ event VestedTokensFor(address indexed beneficiary, address fund, uint256 tokenAmount); /** * event for finalize function call at the end of the crowdsale */ event Finalized(); /** * event for token minting for private investors * @param beneficiary who will get the tokens once they are vested * @param tokenAmount amount of tokens purchased */ event MintedTokensFor(address indexed beneficiary, uint256 tokenAmount); /** * @dev Contract constructor function * @param _startTime The timestamp of the beginning of the crowdsale * @param _endTime Timestamp when the crowdsale will finish * @param _rate The token rate per ETH * Percent value is saved in crowdsalePercent. * @param _wallet Multisig wallet that will hold the crowdsale funds. * @param _whiteListRegistry Address of the whitelist registry contract */ function LuckCashCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _whiteListRegistry) public CappedCrowdsale(CAP.mul(325).div(1000)) PoolSegregationCrowdsale(CAP) FinalizableCappedCrowdsale() Crowdsale(_startTime, _endTime, _rate, _wallet) { require(_whiteListRegistry != address(0)); whitelistRegistry = WhiteListRegistry(_whiteListRegistry); LuckCashToken(token).pause(); } /** * @dev Creates LuckCashToken contract. This is called on the Crowdsale contract constructor */ function createTokenContract() internal returns(MintableToken) { return new LuckCashToken(CAP); // 600 million cap } /** * @dev Mintes fresh token for a private investor. * @param beneficiary The beneficiary of the minting * @param amount The total token amount to be minted */ function mintTokensFor(address beneficiary, uint256 amount, uint poolId) external onlyOwner onlyIfInPool(amount, poolId) { require(beneficiary != address(0) && amount != 0); // require(now <= endTime); token.mint(beneficiary, amount); MintedTokensFor(beneficiary, amount); } /** * @dev Creates a new contract for a vesting fund that will release funds for the beneficiary every quarter * @param beneficiary The beneficiary of the funds * @param amount The total token amount to be vested * @param quarters The number of quarters over which the funds will vest. Every quarter a sum equal to amount.quarters will be release */ function createVestFundFor(address beneficiary, uint256 amount, uint256 quarters, uint poolId) external onlyOwner onlyIfInPool(amount, poolId) { require(beneficiary != address(0) && amount != 0); require(quarters > 0); // require(now <= endTime); VestingFund fund = new VestingFund(beneficiary, endTime, quarters, token); // the vesting period starts when the crowdsale has ended token.mint(fund, amount); VestedTokensFor(beneficiary, fund, amount); } /** * @dev overrides Crowdsale#validPurchase to add whitelist logic * @return true if buyers is able to buy at the moment */ function validPurchase() internal view returns(bool) { return super.validPurchase() && canContributeAmount(msg.sender, msg.value); } function transferFromCrowdsaleToUserAdoptionPool() public onlyOwner { require(now > endTime); super.transferRemainingTokensToUserAdoptionPool(super.getTokenAmount(cap) - super.getTokenAmount(weiRaised)); } /** * @dev finalizes crowdsale */ function finalization() internal { token.finishMinting(); LuckCashToken(token).unpause(); wallet.transfer(this.balance); super.finalization(); } /** * @dev overrides Crowdsale#forwardFunds to report of funds transfer and not transfer into the wallet untill the end */ function forwardFunds() internal { reportContribution(msg.sender, msg.value); } function canContributeAmount(address _contributor, uint _amount) internal view returns (bool) { uint totalAmount = contributions[_contributor].add(_amount); return whitelistRegistry.isAmountAllowed(_contributor, totalAmount); } function reportContribution(address _contributor, uint _amount) internal returns (bool) { contributions[_contributor] = contributions[_contributor].add(_amount); } } contract VestingFund is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); // beneficiary of tokens after they are released address public beneficiary; ERC20Basic public token; uint256 public quarters; uint256 public start; uint256 public released; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, tokens are release in an incremental fashion after a quater has passed until _start + _quarters * 3 * months. * By then all of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _quarters number of quarters the vesting will last * @param _token ERC20 token which is being vested */ function VestingFund(address _beneficiary, uint256 _start, uint256 _quarters, address _token) public { require(_beneficiary != address(0) && _token != address(0)); require(_quarters > 0); beneficiary = _beneficiary; quarters = _quarters; start = _start; token = ERC20Basic(_token); } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0); released = released.add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns(uint256) { return vestedAmount().sub(released); } /** * @dev Calculates the amount that has already vested. */ function vestedAmount() public view returns(uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released); if (now < start) { return 0; } uint256 dT = now.sub(start); // time passed since start uint256 dQuarters = dT.div(90 days); // quarters passed if (dQuarters >= quarters) { return totalBalance; // return everything if vesting period ended } else { return totalBalance.mul(dQuarters).div(quarters); // ammount = total * (quarters passed / total quarters) } } } contract WhiteListRegistry is Ownable { mapping (address => WhiteListInfo) public whitelist; using SafeMath for uint; struct WhiteListInfo { bool whiteListed; uint minCap; uint maxCap; } event AddedToWhiteList( address contributor, uint minCap, uint maxCap ); event RemovedFromWhiteList( address _contributor ); function addToWhiteList(address _contributor, uint _minCap, uint _maxCap) public onlyOwner { require(_contributor != address(0)); whitelist[_contributor] = WhiteListInfo(true, _minCap, _maxCap); AddedToWhiteList(_contributor, _minCap, _maxCap); } function removeFromWhiteList(address _contributor) public onlyOwner { require(_contributor != address(0)); delete whitelist[_contributor]; RemovedFromWhiteList(_contributor); } function isWhiteListed(address _contributor) public view returns(bool) { return whitelist[_contributor].whiteListed; } function isAmountAllowed(address _contributor, uint _amount) public view returns(bool) { return whitelist[_contributor].maxCap >= _amount && whitelist[_contributor].minCap <= _amount && isWhiteListed(_contributor); } } contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract LuckCashToken is PausableToken, CappedToken { string public constant name = "LuckCash"; string public constant symbol = "LCK"; uint8 public constant decimals = 18; function LuckCashToken(uint _cap) public CappedToken(_cap) PausableToken() { } }
Must be called after crowdsale ends, to do some extra finalization work. Calls the contract's finalization function./
function finalize() onlyOwnerOrAfterReconciliation public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; }
295,547
./partial_match/1/0x131157c6760f78f7dDF877C0019Eba175BA4b6F6/sources/bigsb-token.sol
Total fees collected
function totalFees() external view returns (uint256) { return _tFeeTotal; }
3,942,087
./full_match/5/0xcc65Ea1d651ee8ACA6B8a0ba140221032aB73380/sources/lottoTickets.sol
finds ticket number owner uses binary search (as opposed to linear/jump/interpolation). "unchecked" as there'd be no way to overflow/underflow/divide by zero (supposedly). there's a lot of lingo on the "net", but what I've found is that binary search is well worth it even with only a small array length. I've heard interpolation can be better but I'm not sure if it would be worth it in solidity because of all the mathematical equations it'd have to solve- even if it runs fewer times it might be more gas intensive. ticketId of the ticket who's address we are trying to find return address of the person who's ticket we had Finds the owner of a ticket with a given ID. ticketId The ID of the ticket to find the owner of. return The address of the owner of the ticket./ The function is marked as internal and view and returns the address of the owner The unchecked block is used to disable Solidity's overflow checking for the duration of the block Enter a while loop that continues as long as mid is less than len If ticketId is greater than the value at index mid in _bundleFirstTicketNum If ticketId is less than the value at index mid in _bundleFirstTicketNum If ticketId is also less than the value at index mid - 1 in _bundleFirstTicketNum If ticketId is greater than or equal to the value at index mid - 1 in _bundleFirstTicketNum If ticketId is equal to the value at index mid in _bundleFirstTicketNum
function _findTicketOwner( ) internal view returns (address) { unchecked { while (mid < len) { if (ticketId > _bundleFirstTicketNum[mid]) { } else if (ticketId < _bundleFirstTicketNum[mid]) { if (ticketId < _bundleFirstTicketNum[mid - 1]) { } else if (ticketId >= _bundleFirstTicketNum[mid - 1]) { } } else if (ticketId == _bundleFirstTicketNum[mid]) { } } } }
7,085,008
./partial_match/1/0xb2D2F8F7d6C448E80baE12f897544Dd148f94143/sources/IVTUser.sol
是否包含交易Id _transactionId _transactionTime to get return {[bool]}/
function hasTransactionId(uint256 _transactionId) public view returns (bool) { return transactions[_transactionId]; }
9,123,352
./full_match/80001/0x21D60df173aE9FB6C68929baE578968aD5f2EFfC/sources/contracts/Gateway/ClaimGateway.sol
_coverId _roundId number attribute from subgraph/ msg.sender must cover's owner get startAt & endAt of Cover cover must start cover must be still active make sure there is no valid claim Cannot use same roundId to submit claim on cover Note : Limit only able to make 1 valid claim &$ cannot make multiple valid claim Price feed aggregator Call aggregator NOTE : comment out when testing validate timestamp of price feed, time of round id must in range of cover period NOTE : comment out when testing Check 1 hours before roundId, make sure the devaluation id valid add filing claim + 1 hours is a buffer time Check validity and make payout
function submitClaim(uint256 _coverId, uint80 _roundId) external { InsuranceCover memory cover = coverData.getCoverById(_coverId); require(cover.holder == msg.sender, "Claim Gateway: Not cover's owner"); uint256 startAt = coverGateway.getStartAt(_coverId); uint256 endAt = coverGateway.getEndAt(_coverId); require(startAt != 0, "Claim Gateway: Cover not started yet"); require( startAt <= block.timestamp && block.timestamp <= endAt, "Claim Gateway: Cover is not active" ); require( !claimData.isValidClaimExists(_coverId), "Claim Gateway : Valid claim exists" ); require( claimData.uniqueRoundId(_coverId, _roundId), "Claim Gateway: Cannot use same round id" ); address priceFeedAddr = claimHelper.getPriceFeedAddress(cover); AggregatorV3Interface priceFeed = AggregatorV3Interface(priceFeedAddr); (, , , uint256 eventTimestamp, ) = priceFeed.getRoundData(_roundId); require( startAt <= eventTimestamp && eventTimestamp <= endAt, "Claim Gateway: Invalid time of price feed" ); require( claimHelper.isValidPastDevaluation(priceFeedAddr, _roundId), "Claim Gateway: Previous round not devaluation" ); uint256 claimId = claimData.addClaim( _coverId, _roundId, eventTimestamp, msg.sender ); if ((eventTimestamp + MONITORING_PERIOD) + 1 hours <= block.timestamp) { _checkValidityAndPayout(claimId, priceFeedAddr); } }
9,463,422
./partial_match/1/0x8eFFDb6d5FC981DaB013E78184863E9024890712/sources/GladiatorPepe.sol
Create a uniswap pair for this new token exclude from paying fees or having max transaction amount
constructor() ERC20("Gladiator Pepe","GPEPE") { address newOwner = address(0x5AD2f817F6Ac0F00e5a4ccAEECccf69612Bab989); uint256 totalSupply = 420689899999998 * 10**18; maxTransactionAmount = totalSupply * 2 / 100; swapTokensAtAmount = totalSupply / 1000; maxWallet = totalSupply * 6 / 100; marketingSellFee = 3; liquiditySellFee = 1; totalSellFees = marketingSellFee + liquiditySellFee; marketingBuyFee = 3; liquidityBuyFee = 1; totalBuyFees = marketingBuyFee + liquidityBuyFee; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); createInitialSupply is a function that is only called here, and CANNOT be called ever again createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner);
9,371,892
//Address: 0x51e4e00e3e019e58fc0b8cc8c6490a2d28efbf44 //Contract name: SanityPools //Balance: 0 Ether //Verification Date: 12/7/2017 //Transacion Count: 11 // CODE STARTS HERE pragma solidity ^0.4.15; /* author : dungeon A contract for doing pools with only one contract. */ // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function transfer(address _to, uint256 _value) returns (bool success); function balanceOf(address _owner) constant returns (uint256 balance); } contract Controller { //The addy of the developer address public developer = 0xEE06BdDafFA56a303718DE53A5bc347EfbE4C68f; modifier onlyOwner { require(msg.sender == developer); _; } } contract SanityPools is Controller { //mapping of the pool's index with the corresponding balances mapping (uint256 => mapping (address => uint256)) balances; //Array of 100 pools max Pool[100] pools; //Index of the active pool uint256 index_active = 0; //Allows an emergency withdraw after 1 week after the buy : 7*24*60*60 / 15.3 (mean time for mining a block) uint256 public week_in_blocs = 39529; modifier validIndex(uint256 _index){ require(_index <= index_active); _; } struct Pool { string name; //0 means there is no min/max amount uint256 min_amount; uint256 max_amount; // address sale; ERC20 token; // Record ETH value of tokens currently held by contract for the pool. uint256 pool_eth_value; // Track whether the pool has bought the tokens yet. bool bought_tokens; uint256 buy_block; } //Functions reserved for the owner function createPool(string _name, uint256 _min, uint256 _max) onlyOwner { require(index_active < 100); //Creates a new struct and saves in storage pools[index_active] = Pool(_name, _min, _max, 0x0, ERC20(0x0), 0, false, 0); //updates the active index index_active += 1; } function setSale(uint256 _index, address _sale) onlyOwner validIndex(_index) { Pool storage pool = pools[_index]; require(pool.sale == 0x0); pool.sale = _sale; } function setToken(uint256 _index, address _token) onlyOwner validIndex(_index) { Pool storage pool = pools[_index]; pool.token = ERC20(_token); } function buyTokens(uint256 _index) onlyOwner validIndex(_index) { Pool storage pool = pools[_index]; require(pool.pool_eth_value >= pool.min_amount); require(pool.pool_eth_value <= pool.max_amount || pool.max_amount == 0); require(!pool.bought_tokens); //Prevent burning of ETH by mistake require(pool.sale != 0x0); //Registers the buy block number pool.buy_block = block.number; // Record that the contract has bought the tokens. pool.bought_tokens = true; // Transfer all the funds to the crowdsale address. pool.sale.transfer(pool.pool_eth_value); } function emergency_withdraw(uint256 _index, address _token) onlyOwner validIndex(_index) { //Allows to withdraw all the tokens after a certain amount of time, in the case //of an unplanned situation Pool storage pool = pools[_index]; require(block.number >= (pool.buy_block + week_in_blocs)); ERC20 token = ERC20(_token); uint256 contract_token_balance = token.balanceOf(address(this)); require (contract_token_balance != 0); // Send the funds. Throws on failure to prevent loss of funds. require(token.transfer(msg.sender, contract_token_balance)); } function change_delay(uint256 _delay) onlyOwner { week_in_blocs = _delay; } //Functions accessible to everyone function getPoolName(uint256 _index) validIndex(_index) constant returns (string) { Pool storage pool = pools[_index]; return pool.name; } function refund(uint256 _index) validIndex(_index) { Pool storage pool = pools[_index]; //Can't refund if tokens were bought require(!pool.bought_tokens); uint256 eth_to_withdraw = balances[_index][msg.sender]; //Updates the user's balance prior to sending ETH to prevent recursive call. balances[_index][msg.sender] = 0; //Updates the pool ETH value pool.pool_eth_value -= eth_to_withdraw; msg.sender.transfer(eth_to_withdraw); } function withdraw(uint256 _index) validIndex(_index) { Pool storage pool = pools[_index]; // Disallow withdraw if tokens haven't been bought yet. require(pool.bought_tokens); uint256 contract_token_balance = pool.token.balanceOf(address(this)); // Disallow token withdrawals if there are no tokens to withdraw. require(contract_token_balance != 0); // Store the user's token balance in a temporary variable. uint256 tokens_to_withdraw = (balances[_index][msg.sender] * contract_token_balance) / pool.pool_eth_value; // Update the value of tokens currently held by the contract. pool.pool_eth_value -= balances[_index][msg.sender]; // Update the user's balance prior to sending to prevent recursive call. balances[_index][msg.sender] = 0; //The 1% fee uint256 fee = tokens_to_withdraw / 100; // Send the funds. Throws on failure to prevent loss of funds. require(pool.token.transfer(msg.sender, tokens_to_withdraw - fee)); // Send the fee to the developer. require(pool.token.transfer(developer, fee)); } function contribute(uint256 _index) validIndex(_index) payable { Pool storage pool = pools[_index]; require(!pool.bought_tokens); //Check if the contribution is within the limits or if there is no max amount require(pool.pool_eth_value+msg.value <= pool.max_amount || pool.max_amount == 0); //Update the eth held by the pool pool.pool_eth_value += msg.value; //Updates the user's balance balances[_index][msg.sender] += msg.value; } }
Functions accessible to everyone
function getPoolName(uint256 _index) validIndex(_index) constant returns (string) { Pool storage pool = pools[_index]; return pool.name; }
993,072
/* Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "./interfaces/ISTokensV2.sol"; import "./interfaces/IUTokensV2.sol"; import "./interfaces/ILiquidStakingV2.sol"; import "./libraries/FullMath.sol"; contract LiquidStakingV2 is ILiquidStakingV2, PausableUpgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using FullMath for uint256; //Private instances of contracts to handle Utokens and Stokens IUTokensV2 public _uTokens; ISTokensV2 public _sTokens; // defining the fees and minimum values uint256 private _minStake; uint256 private _minUnstake; uint256 private _stakeFee; uint256 private _unstakeFee; uint256 public _valueDivisor; // constants defining access control ROLES bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // variables pertaining to unbonding logic uint256 private _unstakingLockTime; uint256 private _epochInterval; uint256 private _unstakeEpoch; uint256 private _unstakeEpochPrevious; //Mapping to handle the Expiry period mapping(address => uint256[]) public _unstakingExpiration; //Mapping to handle the Expiry amount mapping(address => uint256[]) public _unstakingAmount; //mappint to handle a counter variable indicating from what index to start the loop. mapping(address => uint256) public _withdrawCounters; // variable pertaining to contract upgrades versioning uint256 public _version; uint256 public _batchingLimit; /** * @dev Constructor for initializing the LiquidStaking contract. * @param uAddress - address of the UToken contract. * @param sAddress - address of the SToken contract. * @param pauserAddress - address of the pauser admin. * @param unstakingLockTime - varies from 21 hours to 21 days. * @param epochInterval - varies from 3 hours to 3 days. * @param valueDivisor - valueDivisor set to 10^9. */ function initialize( address uAddress, address sAddress, address pauserAddress, uint256 unstakingLockTime, uint256 epochInterval, uint256 valueDivisor ) public virtual initializer { __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, pauserAddress); setUTokensContract(uAddress); setSTokensContract(sAddress); setUnstakingLockTime(unstakingLockTime); setMinimumValues(1, 1); _valueDivisor = valueDivisor; setUnstakeEpoch(block.timestamp, block.timestamp, epochInterval); } /** * @dev Set 'fees', called from admin * @param stakeFee: stake fee * @param unstakeFee: unstake fee * * Emits a {SetFees} event with 'fee' set to the stake and unstake. * */ function setFees(uint256 stakeFee, uint256 unstakeFee) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ1"); // range checks for fees. Since fee cannot be more than 100%, the max cap // is _valueDivisor * 100, which then brings the fees to 100 (percentage) require( (stakeFee <= _valueDivisor.mul(100) || stakeFee == 0) && (unstakeFee <= _valueDivisor.mul(100) || unstakeFee == 0), "LQ2" ); _stakeFee = stakeFee; _unstakeFee = unstakeFee; emit SetFees(stakeFee, unstakeFee); return true; } /** * @dev Set 'unstake props', called from admin * @param unstakingLockTime: varies from 21 hours to 21 days * * Emits a {SetUnstakeProps} event with 'fee' set to the stake and unstake. * */ function setUnstakingLockTime(uint256 unstakingLockTime) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ3"); _unstakingLockTime = unstakingLockTime; emit SetUnstakingLockTime(unstakingLockTime); return true; } /** * @dev get fees, min values, value divisor and epoch props * */ function getStakeUnstakeProps() public view virtual override returns ( uint256 stakeFee, uint256 unstakeFee, uint256 minStake, uint256 minUnstake, uint256 valueDivisor, uint256 epochInterval, uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 unstakingLockTime ) { stakeFee = _stakeFee; unstakeFee = _unstakeFee; minStake = _minStake; minUnstake = _minStake; valueDivisor = _valueDivisor; epochInterval = _epochInterval; unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; unstakingLockTime = _unstakingLockTime; } /** * @dev Set 'minimum values', called from admin * @param minStake: stake minimum value * @param minUnstake: unstake minimum value * * Emits a {SetMinimumValues} event with 'minimum value' set to the stake and unstake. * */ function setMinimumValues(uint256 minStake, uint256 minUnstake) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ4"); require(minStake >= 1, "LQ5"); require(minUnstake >= 1, "LQ6"); _minStake = minStake; _minUnstake = minUnstake; emit SetMinimumValues(minStake, minUnstake); return true; } /** * @dev Set 'unstake epoch', called from admin * @param unstakeEpoch: unstake epoch * @param unstakeEpochPrevious: unstake epoch previous(initially set to same value as unstakeEpoch) * @param epochInterval: varies from 3 hours to 3 days * * Emits a {SetUnstakeEpoch} event with 'unstakeEpoch' * */ function setUnstakeEpoch( uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 epochInterval ) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ7"); require(unstakeEpochPrevious <= unstakeEpoch, "LQ8"); if (unstakeEpoch == 0 && epochInterval != 0) revert("LQ9"); _unstakeEpoch = unstakeEpoch; _unstakeEpochPrevious = unstakeEpochPrevious; _epochInterval = epochInterval; emit SetUnstakeEpoch(unstakeEpoch, unstakeEpochPrevious, epochInterval); return true; } /** * @dev Set 'contract address', called from constructor * @param uAddress: utoken contract address * * Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address. * */ function setUTokensContract(address uAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ10"); _uTokens = IUTokensV2(uAddress); emit SetUTokensContract(uAddress); } /** * @dev Set 'contract address', called from constructor * @param sAddress: stoken contract address * * Emits a {SetSTokensContract} event with '_contract' set to the stoken contract address. * */ function setSTokensContract(address sAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ11"); _sTokens = ISTokensV2(sAddress); emit SetSTokensContract(sAddress); } /** * @dev Stake utokens over the platform with address 'to' for desired 'amount'(Burn uTokens and Mint sTokens) * @param to: user address for staking, amount: number of tokens to stake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {StakeTokens} event * */ function stake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than minimum stake value require(to == _msgSender(), "LQ12"); // Check the current balance for uTokens is greater than the amount to be staked uint256 _currentUTokenBalance = _uTokens.balanceOf(to); uint256 _stakeFeeAmount = (amount.mulDiv(_stakeFee, _valueDivisor)).div( 100 ); uint256 _finalTokens = amount.add(_stakeFeeAmount); // the value which should be greater than or equal to _minStake // is amount since minval applies to number of sTokens to be minted require(amount >= _minStake, "LQ13"); require(_currentUTokenBalance >= _finalTokens, "LQ14"); emit StakeTokens(to, amount, _finalTokens, block.timestamp); // Burn the uTokens as specified with the amount _uTokens.burn(to, _finalTokens); // Mint the sTokens for the account specified _sTokens.mint(to, amount); return true; } /** * @dev UnStake stokens over the platform with address 'to' for desired 'amount' (Burn sTokens and Mint uTokens with 21 days locking period) * @param to: user address for staking, amount: number of tokens to unstake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {UnstakeTokens} event * */ function unStake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than 0 require(to == _msgSender(), "LQ15"); // Check the current balance for sTokens is greater than the amount to be unStaked uint256 _currentSTokenBalance = _sTokens.balanceOf(to); uint256 _unstakeFeeAmount = (amount.mulDiv(_unstakeFee, _valueDivisor)) .div(100); uint256 _finalTokens = amount.add(_unstakeFeeAmount); // the value which should be greater than or equal to _minSUnstake // is amount since minval applies to number of uTokens to be withdrawn require(amount >= _minUnstake, "LQ18"); require(_currentSTokenBalance >= _finalTokens, "LQ19"); // Burn the sTokens as specified with the amount _sTokens.burn(to, _finalTokens); _unstakingExpiration[to].push(block.timestamp); // array will hold amount and not _finalTokens because that is the amount of // uTokens pending to be credited after withdraw period _unstakingAmount[to].push(amount); // the event needs to capture _finalTokens that were and not amount emit UnstakeTokens(to, amount, _finalTokens, block.timestamp); return true; } /** * @dev returns the nearest epoch milestone in the future */ function getUnstakeEpochMilestone(uint256 _unstakeTimestamp) public view virtual override returns (uint256 unstakeEpochMilestone) { if (_unstakeTimestamp == 0) return 0; // if epoch values are not relevant, then the epoch milestone is the unstake timestamp itself (backward compatibility) if ( (_unstakeEpoch == 0 && _unstakeEpochPrevious == 0) || _epochInterval == 0 ) return _unstakeTimestamp; if (_unstakeEpoch > _unstakeTimestamp) return (_unstakeEpoch); uint256 _referenceStartTime = (_unstakeTimestamp).add( _unstakeEpoch.sub(_unstakeEpochPrevious) ); uint256 _timeDiff = _referenceStartTime.sub(_unstakeEpoch); unstakeEpochMilestone = (_timeDiff.mod(_epochInterval)).add( _referenceStartTime ); return (unstakeEpochMilestone); } /** * @dev returns the time left for unbonding to finish */ function getUnstakeTime(uint256 _unstakeTimestamp) public view virtual override returns ( uint256 unstakeTime, uint256 unstakeEpoch, uint256 unstakeEpochPrevious ) { uint256 _unstakeEpochMilestone = getUnstakeEpochMilestone( _unstakeTimestamp ); if (_unstakeEpochMilestone == 0) return (0, unstakeEpoch, unstakeEpochPrevious); unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; //adding unstakingLockTime with epoch difference unstakeTime = _unstakeEpochMilestone.add(_unstakingLockTime); return (unstakeTime, unstakeEpoch, unstakeEpochPrevious); } /** * @dev Lock the unstaked tokens for 21 days, user can withdraw the same (Mint uTokens with 21 days locking period) * * @param staker: user address for withdraw * * Requirements: * * - `current block timestamp` should be after 21 days from the period where unstaked function is called. * * Emits a {WithdrawUnstakeTokens} event * */ function withdrawUnstakedTokens(address staker) public virtual override whenNotPaused { require(staker == _msgSender(), "LQ20"); uint256 _withdrawBalance; uint256 _counter = _withdrawCounters[staker]; uint256 _counter2 = _withdrawCounters[staker]; uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length > _batchingLimit.add(_counter) ? _batchingLimit.add(_counter) : _unstakingExpiration[staker].length; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then add the balance and then mint uTokens _withdrawBalance = _withdrawBalance.add( _unstakingAmount[staker][i] ); delete _unstakingExpiration[staker][i]; delete _unstakingAmount[staker][i]; _counter2 = _counter2.add(1); } } // update _withdrawCounters[staker] only once outside for loop to save gas _withdrawCounters[staker] = _counter2; require(_withdrawBalance > 0, "LQ21"); emit WithdrawUnstakeTokens(staker, _withdrawBalance, block.timestamp); _uTokens.mint(staker, _withdrawBalance); } /** * @dev get Total Unbonded Tokens * @param staker: account address * */ function getTotalUnbondedTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev get Total Unbonding Tokens * @param staker: account address * */ function getTotalUnbondingTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp < _getUnstakeTime) { //if 21 days + epoch difference have not passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev Set 'batching limit', called from admin * @param batchingLimit: batching limit * * Emits a {SetBatchingLimit} event. * */ function setBatchingLimit(uint256 batchingLimit) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ24"); _batchingLimit = batchingLimit; emit SetBatchingLimit(batchingLimit, block.timestamp); success = true; return success; } /** * @dev get batching limit * */ function getBatchingLimit() public view virtual override returns (uint256 batchingLimit) { batchingLimit = _batchingLimit; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ22"); _pause(); return true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ23"); _unpause(); return true; } }
returns the nearest epoch milestone in the future/ if epoch values are not relevant, then the epoch milestone is the unstake timestamp itself (backward compatibility)
function getUnstakeEpochMilestone(uint256 _unstakeTimestamp) public view virtual override returns (uint256 unstakeEpochMilestone) { if (_unstakeTimestamp == 0) return 0; if ( (_unstakeEpoch == 0 && _unstakeEpochPrevious == 0) || _epochInterval == 0 ) return _unstakeTimestamp; if (_unstakeEpoch > _unstakeTimestamp) return (_unstakeEpoch); uint256 _referenceStartTime = (_unstakeTimestamp).add( _unstakeEpoch.sub(_unstakeEpochPrevious) ); uint256 _timeDiff = _referenceStartTime.sub(_unstakeEpoch); unstakeEpochMilestone = (_timeDiff.mod(_epochInterval)).add( _referenceStartTime ); return (unstakeEpochMilestone); }
5,473,711
./full_match/1/0x151522484121f4e28eA24c8b5d827132775a93FE/sources/contracts/periphery/UniswapV2Router01.sol
ADD LIQUIDITY create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal returns (uint amountA, uint amountB) { if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, "SweepnFlipRouter: INSUFFICIENT_B_AMOUNT"); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, "SweepnFlipRouter: INSUFFICIENT_A_AMOUNT"); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
17,006,256
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ITreasury.sol"; import "../utils/ContractGuard.sol"; import "../Authorizable.sol"; // Note that this pool has no minter key of GAME (rewards). // Instead, the governance will call GAME distributeReward method and send reward to this pool at the beginning. contract GameGenesisRewardPool is Authorizable, ContractGuard { using SafeMath for uint256; using SafeERC20 for IERC20; ITreasury public treasury; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. GAME to distribute. uint256 lastRewardTime; // Last time that GAME distribution occurs. uint256 accGamePerShare; // Accumulated GAME per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public game; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The time when GAME mining starts. uint256 public poolStartTime; // The time when GAME mining ends. uint256 public poolEndTime; // MAINNET uint256 public gamePerSecond = 0.09645 ether; // Approximately 25000 GAME / (72h * 60min * 60s) uint256 public runningTime = 3 days; // 3 days uint256 public depositFee = 100; // END MAINNET event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _game, ITreasury _treasury, uint256 _poolStartTime ) public { require(block.timestamp < _poolStartTime, "late"); if (_game != address(0)) game = IERC20(_game); treasury = _treasury; poolStartTime = _poolStartTime; poolEndTime = poolStartTime + runningTime; } // Allow us to delay or begin earlier if we have not started yet. Careful of gas. function setPoolStartTime( uint256 _time ) public onlyAuthorized { require(block.timestamp < poolStartTime, "Already started."); require(block.timestamp < _time, "Time input is too early."); uint256 length = poolInfo.length; uint256 pid = 0; uint256 _lastRewardTime; for (pid = 0; pid < length; pid += 1) { PoolInfo storage pool = poolInfo[pid]; _lastRewardTime = pool.lastRewardTime; if (_lastRewardTime == poolStartTime || _lastRewardTime < _time) { pool.lastRewardTime = _time; } } poolStartTime = _time; } function setPoolEndTime( uint256 _time ) public onlyAuthorized { require(block.timestamp < poolStartTime, "Already started."); require(poolStartTime < _time, "Time input is too early."); poolEndTime = _time; runningTime = poolEndTime - poolStartTime; } function checkPoolDuplicate(IERC20 _token) internal view { uint256 length = poolInfo.length; uint256 pid; for (pid = 0; pid < length; pid += 1) { require(poolInfo[pid].token != _token, "GameGenesisRewardPool: existing pool?"); } } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, uint256 _lastRewardTime ) public onlyOperator { checkPoolDuplicate(_token); if (_withUpdate) { massUpdatePools(); } if (block.timestamp < poolStartTime) { // chef is sleeping if (_lastRewardTime < poolStartTime) { _lastRewardTime = poolStartTime; } } else { // chef is cooking if (_lastRewardTime < block.timestamp) { _lastRewardTime = block.timestamp; } } bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp); poolInfo.push(PoolInfo({ token : _token, allocPoint : _allocPoint, lastRewardTime : _lastRewardTime, accGamePerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's GAME allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } function setDepositFee(uint256 _depositFee) public onlyOperator { require(_depositFee <= 100, "Deposit fee must be less than 1%"); depositFee = _depositFee; } function getGamePerSecondInPool(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 _poolGamePerSecond = gamePerSecond.mul(pool.allocPoint).div(totalAllocPoint); return _poolGamePerSecond; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) { if (_fromTime >= _toTime) return 0; if (_toTime >= poolEndTime) { if (_fromTime >= poolEndTime) return 0; if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(gamePerSecond); return poolEndTime.sub(_fromTime).mul(gamePerSecond); } else { if (_toTime <= poolStartTime) return 0; if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(gamePerSecond); return _toTime.sub(_fromTime).mul(gamePerSecond); } } // View function to see pending GAME on frontend. function pendingGAME(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGamePerShare = pool.accGamePerShare; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _gameReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accGamePerShare = accGamePerShare.add(_gameReward.mul(1e18).div(tokenSupply)); } return user.amount.mul(accGamePerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() internal { // Too scared of scary reentrancy warnings. Internal version. uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables for all pools. Be careful of gas spending! function forceMassUpdatePools() external onlyAuthorized { // Too scared of scary reentrancy warnings. External version. massUpdatePools(); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal { // Too scared of scary reentrancy warnings. Internal version. PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { pool.lastRewardTime = block.timestamp; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); // Reentrancy issue? But this can't be used maliciously... Can it? A malicious token is what we should be more worried about. } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _gameReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accGamePerShare = pool.accGamePerShare.add(_gameReward.mul(1e18).div(tokenSupply)); } pool.lastRewardTime = block.timestamp; } // Update reward variables of the given pool to be up-to-date. function forceUpdatePool(uint256 _pid) external onlyAuthorized { // Too scared of scary reentrancy warnings. External version. updatePool(_pid); } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public onlyOneBlock { // Poor smart contracts, can't deposit to multiple pools at once... But my OCD will not allow this. address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accGamePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeGameTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { uint256 feeAmount = _amount.mul(depositFee).div(10000); uint256 amountToDeposit = _amount.sub(feeAmount); if(feeAmount > 0) pool.token.safeTransferFrom(_sender, treasury.daoFund(), feeAmount); pool.token.safeTransferFrom(_sender, address(this), amountToDeposit); user.amount = user.amount.add(amountToDeposit); } user.rewardDebt = user.amount.mul(pool.accGamePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. // No withdrawal fees or locks for Genesis Pools. function withdraw(uint256 _pid, uint256 _amount) public onlyOneBlock { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accGamePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeGameTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accGamePerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public onlyOneBlock { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.token.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe GAME transfer function, just in case if rounding error causes pool to not have enough GAMEs. function safeGameTransfer(address _to, uint256 _amount) internal { uint256 _gameBalance = game.balanceOf(address(this)); if (_gameBalance > 0) { if (_amount > _gameBalance) { game.safeTransfer(_to, _gameBalance); } else { game.safeTransfer(_to, _amount); } } } function getRequiredAllocation() public view returns (uint256) { uint256 _generatedReward = getGeneratedReward(poolStartTime, poolEndTime); return _generatedReward; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.timestamp < poolEndTime + 90 days) { // do not allow to drain core token (GAME or lps) if less than 90 days after pool ends require(_token != game, "game"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.token, "pool.token"); } } _token.safeTransfer(to, amount); } }
Allow us to delay or begin earlier if we have not started yet. Careful of gas.
function setPoolStartTime( uint256 _time ) public onlyAuthorized { require(block.timestamp < poolStartTime, "Already started."); require(block.timestamp < _time, "Time input is too early."); uint256 length = poolInfo.length; uint256 pid = 0; uint256 _lastRewardTime; for (pid = 0; pid < length; pid += 1) { PoolInfo storage pool = poolInfo[pid]; _lastRewardTime = pool.lastRewardTime; if (_lastRewardTime == poolStartTime || _lastRewardTime < _time) { pool.lastRewardTime = _time; } } poolStartTime = _time; }
5,537,199
/** *Submitted for verification at Etherscan.io on 2021-02-05 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); } interface IyVault { function token() external view returns (address); function deposit(uint, address) external returns (uint); function withdraw(uint, address, uint) external returns (uint); function permit(address, address, uint, uint, bytes32) external view returns (bool); function pricePerShare() external view returns (uint); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract yAffiliateTokenV2 { using SafeERC20 for IERC20; /// @notice EIP-20 token name for this token string public name; /// @notice EIP-20 token symbol for this token string public symbol; /// @notice EIP-20 token decimals for this token uint256 public decimals; /// @notice Total number of tokens in circulation uint public totalSupply = 0; mapping(address => mapping (address => uint)) internal allowances; mapping(address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); uint public index = 0; uint public bal = 0; function update() external { _update(); } function _update() internal { if (totalSupply > 0) { uint256 _bal = IyVault(vault).pricePerShare(); if (_bal > bal) { uint256 _diff = _bal - bal; if (_diff > 0) { uint256 _ratio = _diff * 10**decimals / totalSupply; if (_ratio > 0) { index += _ratio; bal = _bal; } } } } else { bal = IyVault(vault).pricePerShare(); } } function _mint(address dst, uint amount) internal { // mint the amount totalSupply += amount; // transfer the amount to the recipient balances[dst] += amount; emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { // burn the amount totalSupply -= amount; // transfer the amount from the recipient balances[dst] -= amount; emit Transfer(dst, address(0), amount); } address public affiliate; address public governance; address public pendingGovernance; address public immutable token; address public immutable vault; constructor(address _governance, string memory _moniker, address _affiliate, address _token, address _vault) { DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); affiliate = _affiliate; governance = _governance; token = _token; vault = _vault; name = string(abi.encodePacked(_moniker, "-yearn ", IERC20(_token).name())); symbol = string(abi.encodePacked(_moniker, "-yv", IERC20(_token).symbol())); decimals = IERC20(_token).decimals(); IERC20(_token).approve(_vault, type(uint).max); } function setGovernance(address _gov) external { require(msg.sender == governance); pendingGovernance = _gov; } function acceptGovernance() external { require(msg.sender == pendingGovernance); governance = pendingGovernance; } function currentContribution() external view returns (uint) { return 1e18 * IERC20(vault).balanceOf(address(this)) / IERC20(vault).totalSupply(); } function setAffiliate(address _affiliate) external { require(msg.sender == governance || msg.sender == affiliate); affiliate = _affiliate; } function depositAll() external { _deposit(IERC20(token).balanceOf(msg.sender)); } function deposit(uint amount) external { _deposit(amount); } function _deposit(uint amount) internal { _update(); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); _mint(msg.sender, IyVault(vault).deposit(amount, address(this))); } function withdrawAll(uint maxLoss) external { _withdraw(balances[msg.sender], maxLoss); } function withdraw(uint amount, uint maxLoss) external { _withdraw(amount, maxLoss); } function _withdraw(uint amount, uint maxLoss) internal { _update(); _burn(msg.sender, amount); IyVault(vault).withdraw(amount, msg.sender, maxLoss); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) external returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(block.timestamp <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != type(uint).max) { uint newAllowance = spenderAllowance - amount; allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { balances[src] -= amount; balances[dst] += amount; emit Transfer(src, dst, amount); } function _getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract yAffiliateFactoryV2 { using SafeERC20 for IERC20; address public governance; address public pendingGovernance; address[] public _affiliates; mapping(address => bool) isAffiliate; address[] public _yAffiliateTokens; mapping(address => mapping(address => address[])) affiliateTokens; mapping(address => mapping(address => bool)) isTokenAffiliate; mapping(address => address[]) tokenAffiliates; function yAffiliateTokens() external view returns (address[] memory) { return _yAffiliateTokens; } function affiliates() external view returns (address[] memory) { return _affiliates; } constructor() { governance = msg.sender; } function lookupAffiliates(address token) external view returns (address[] memory) { return tokenAffiliates[token]; } function lookupAffiliateToken(address token, address affiliate) external view returns (address[] memory) { return affiliateTokens[token][affiliate]; } function setGovernance(address _gov) external { require(msg.sender == governance); pendingGovernance = _gov; } function acceptGovernance() external { require(msg.sender == pendingGovernance); governance = pendingGovernance; } function deploy(string memory _moniker, address _affiliate, address _token, address _vault) external { require(msg.sender == governance); if (!isAffiliate[_affiliate]) { _affiliates.push(_affiliate); isAffiliate[_affiliate] = true; } if (!isTokenAffiliate[_token][_affiliate]) { tokenAffiliates[_token].push(_affiliate); isTokenAffiliate[_token][_affiliate] = true; } address _yAffiliateToken = address(new yAffiliateTokenV2(governance, _moniker, _affiliate, _token, _vault)); _yAffiliateTokens.push(_yAffiliateToken); affiliateTokens[_token][_affiliate].push(_yAffiliateToken); } }
EIP-20 token name for this token EIP-20 token symbol for this token EIP-20 token decimals for this token Total number of tokens in circulation The EIP-712 typehash for the contract's domain The EIP-712 typehash for the permit struct used by the contract A record of states for signing / validating signatures
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } uint public index = 0; uint public bal = 0;
2,204,453
./full_match/5/0xbd2b42146E75dDc07c29888DAec04Fb176889685/sources/contracts/ArtStation_v0.2.sol
HOOK: Called before every type of transfer. Ensures that only NFTs offered for sale can be transferred. Enforces payment to the seller and royalty payout. Skipped during minting process./
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal override { super._beforeTokenTransfer(from, to, firstTokenId, batchSize); if (from != address(0)) { require(tokensForSale[firstTokenId], "ArtStation: Token not for sale."); uint256 royalties = currentSalePrices[firstTokenId] * royalty / 1000; uint256 payment = currentSalePrices[firstTokenId] - royalties; USDT.transferFrom(to, royaltyRecipient, royalties); USDT.transferFrom(to, from, payment); } }
1,940,046
./full_match/56/0x8f63A11b8eCa1287E932F048140C0B68a92Bc155/sources/contracts/ForkBabyBUSD.sol
Withdraws the ether distributed to the sender. It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); bool success = IERC20(BUSDToken).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; }
3,244,351
./full_match/80001/0x384acAD9ABE419A30CB3Fd232370fCe79920c1aC/sources/contracts-link/StakeManager.sol
@inheritdoc IStakeManager
function setBurnAddress(address _burnAddress) public override onlyOwner { burnAddress = _burnAddress; emit BurnAddressSet(burnAddress); }
5,678,565
/** * From Ethereum Gold initial * copyleft 2019 * */ pragma solidity >=0.4.22 <0.6.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * The owned contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of user permissions. */ contract owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * Allows the current owner to transfer control of the contract to a newOwner. * NewOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * Interface provided to external calls. */ interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { //Multi-trans need to be added using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // Contract generation time uint public timeBegin; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Initializes contract with initial supply tokens to the creator of the contract. */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract. */ function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * Send `_value` tokens to `_to` from your account. */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * Send `_value` tokens to `_to` in behalf of `_from`. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * Allows `_spender` to spend no more than `_value` tokens in your behalf. */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it. */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Allows callers to bulk transfer tokens. */ function batch(address []toAddr, uint256 []value) public returns (bool){ require(toAddr.length == value.length && toAddr.length >= 1); for(uint256 i = 0 ; i < toAddr.length; i++){ transfer(toAddr[i], value[i]); } } }
Internal transfer, only can be called by this contract./ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
5,543,332
pragma solidity ^0.4.24; import "./utl/SafeMath.sol"; /** * @title A simple implementation of the ERC721 Non-Fungible Token Standard * * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * modified from https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC721 * and from https://github.com/1000ethhomepage/1000ethhomepage-contracts */ contract ERC721Simple { using SafeMath for uint256; // ----------------------------------------------------------------------------------------------------------- // ------------------------------------------------ Variables ------------------------------------------------ // ----------------------------------------------------------------------------------------------------------- uint256 public totalSupply; // Basic references //Mapping from token ID to owner address mapping(uint256 => address) internal tokenIdToOwner; // Mapping from owner to list of owned token IDs mapping(address => uint[]) internal listOfOwnerTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal tokenIndexInOwnerArray; // Mapping from token ID to address approved to transfer the token mapping(uint256 => address) internal approvedAddressToTransferTokenId; // ----------------------------------------------------------------------------------------------------------- // -------------------------------------------------- Events ------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // ----------------------------------------------------------------------------------------------------------- // -------------------------------------------------- Modifiers ---------------------------------------------- // ----------------------------------------------------------------------------------------------------------- modifier onlyExtantToken(uint256 _tokenId) { require(ownerOf(_tokenId) != address(0)); _; } modifier onlyOwnerOfToken(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } // ----------------------------------------------------------------------------------------------------------- // ------------------------------------------------ View functions ------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /// @dev Returns the address currently marked as the owner of _tokenID. function ownerOf(uint256 _tokenId) public view returns (address _owner) { return tokenIdToOwner[_tokenId]; } /// @dev Get the total supply of token held by this contract. function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } /// @dev Gets the balance of the specified address function balanceOf(address _owner) public view returns (uint256 _balance) { return listOfOwnerTokens[_owner].length; } /// @dev Gets the approved address to take ownership of a given token ID function approvedFor(uint256 _tokenId) public view returns (address _approved) { return approvedAddressToTransferTokenId[_tokenId]; } /// @dev Gets the list of tokens owned by a given address function tokensOf(address _owner) public view returns (uint256[]) { return listOfOwnerTokens[_owner]; } // ----------------------------------------------------------------------------------------------------------- // --------------------------------------------- Core Public functions --------------------------------------- // ----------------------------------------------------------------------------------------------------------- /// @dev Assigns the ownership of the NFT with ID _tokenId to _to function transfer(address _to, uint256 _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) { require(_to != address(0)); _clearApprovalAndTransfer(msg.sender, _to, _tokenId); emit Transfer(msg.sender, _to, _tokenId); } /// @dev Grants approval for address _to to transfer the NFT with ID _tokenId. function approve(address _to, uint256 _tokenId) public onlyExtantToken(_tokenId) onlyOwnerOfToken (_tokenId) { require(msg.sender != _to); require(_to != address(0)); approvedAddressToTransferTokenId[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// @dev Remove approval for address _to to transfer the NFT with ID _tokenId. function removeApproval (uint256 _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) { require(approvedAddressToTransferTokenId[_tokenId] != address(0)); _clearTokenApproval(_tokenId); emit Approval(msg.sender, address(0), _tokenId); } /// @dev transfer token From owner to _to function transferFrom(address _to, uint256 _tokenId) public onlyExtantToken(_tokenId) { require(approvedAddressToTransferTokenId[_tokenId] == msg.sender); require(_to != address(0)); emit Transfer(ownerOf(_tokenId), _to, _tokenId); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------- Internal functions ---------------------------------------- // ----------------------------------------------------------------------------------------------------------- // set the new token owner function _setTokenOwner(uint256 _tokenId, address _owner) internal { tokenIdToOwner[_tokenId] = _owner; } // add a token to the new owner list function _addTokenToOwnersList(address _owner, uint256 _tokenId) internal { listOfOwnerTokens[_owner].push(_tokenId); tokenIndexInOwnerArray[_tokenId] = listOfOwnerTokens[_owner].length.sub(1); } // remove token for the last owner list function _removeTokenFromOwnersList(address _owner, uint256 _tokenId) internal { uint256 length = listOfOwnerTokens[_owner].length; // length of owner tokens uint256 index = tokenIndexInOwnerArray[_tokenId]; // index of token in owner array uint256 swapToken = listOfOwnerTokens[_owner][length - 1]; // last token in array listOfOwnerTokens[_owner][index] = swapToken; // last token pushed to the place of the one that was transfered tokenIndexInOwnerArray[swapToken] = index; // update the index of the token we moved delete listOfOwnerTokens[_owner][length - 1]; // remove the case we emptied listOfOwnerTokens[_owner].length--; // shorten the array's length } // when the token move from one user to another, we clear the approval made by the last owner function _clearTokenApproval(uint256 _tokenId) internal { approvedAddressToTransferTokenId[_tokenId] = address(0); } // calls all the internal functions above, to transfer a token from one user to another function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { _clearTokenApproval(_tokenId); _removeTokenFromOwnersList(_from, _tokenId); _setTokenOwner(_tokenId, _to); _addTokenToOwnersList(_to, _tokenId); } }
Assigns the ownership of the NFT with ID _tokenId to _to
function transfer(address _to, uint256 _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) { require(_to != address(0)); _clearApprovalAndTransfer(msg.sender, _to, _tokenId); emit Transfer(msg.sender, _to, _tokenId); }
12,616,923
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
Gets the change in balance for the long side. Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. Long balance cannot go below zero. Cannot pull more margin from the short than is available.
function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); if (longDiff > shortBalance) { longDiff = shortBalance; } }
972,369
./partial_match/1/0x17bC6558834F60236B917408691AB555c6662AD8/sources/CORE_LGE_3.sol
returns WETH value of both reserves (dai and CORE for internal purposes)
function getDAIandCOREReservesValueInETH() internal view returns (uint256 COREValueETH, uint256 DAIValueETH) { (uint256 reserveCORE, uint256 reserveDAI) = (tokenReserves[CORE], tokenReserves[DAI]); COREValueETH = reserveCORE.div(1e8).mul(getWETHValueOf1e8TokenUnits(CORE)); DAIValueETH = reserveDAI.div(1e8).mul(getWETHValueOf1e8TokenUnits(DAI)); }
2,674,136
pragma solidity ^0.4.19; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there&#39;s a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there&#39;s a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * Copyright (c) 2018, DEurovision.eu */ contract Eurovision is usingOraclize { // Use SafeMath library to avoid overflows/underflows using SafeMath for uint256; // List of participating countries. NONE is used for an initial state. enum Countries { NONE, Albania, Armenia, Australia, Austria, Azerbaijan, Belarus, Belgium, Bulgaria, Croatia, Cyprus, Czech_Republic, Denmark, Estonia, Macedonia, Finland, France, Georgia, Germany, Greece, Hungary, Iceland, Ireland, Israel, Italy, Latvia, Lithuania, Malta, Moldova, Montenegro, Norway, Poland, Portugal, Romania, Russia, San_Marino, Serbia, Slovenia, Spain, Sweden, Switzerland, The_Netherlands, Ukraine, United_Kingdom } // Number of participating countries. uint256 public constant NUMBER_OF_COUNTRIES = uint256(Countries.United_Kingdom); // Country that won the contest. uint256 public countryWinnerID; // Staker address -> country ID -> amount. mapping (address => mapping (uint256 => uint256)) public stakes; // Staker address -> total amount of wei received from that address. mapping (address => uint256) public weiReceived; // Reward/Refund claimed? mapping (address => bool) public claimed; // Statistics of each country (stakes amount + number of stakers). Statistics[44] public countryStats; // Country statistics (how many stakers and how much is placed on a specific country). struct Statistics { uint256 amount; uint256 numberOfStakers; } // Deadline to stake is the start of the 1st semi-final: May 8th, 7 pm GMT. uint256 public constant STAKE_DEADLINE = 1525806000; // Winner should be announced until: May 18th, 7 pm GMT. uint256 public constant ANNOUNCE_WINNER_DEADLINE = 1526670000; // Rewards/Refunds should be claimed until: June 8th, 7 pm GMT. uint256 public constant CLAIM_DEADLINE = 1528484400; // If the winner was queried at least 3 times < 24 hours before the deadline but // no result received from the callback, allow announcing it manually. uint256 private attemptsToQueryInLast24Hours = 0; uint256 private MIN_NUMBER_OF_ATTEMPTS_TO_WAIT = 3; // Time when the last query was sent to Oraclize. uint256 private lastQueryTime; // Wait the callback for at least 30 mins. uint256 private constant MIN_CALLBACK_WAIT_TIME = 30 minutes; // Only 0.002 Ether or more is allowed. uint256 public constant MIN_STAKE = 0.002 ether; // The sum of all amounts of stakes. uint256 public totalPot = 0; // If the winner is confirmed, participants can start claiming their winnings. bool public winnerConfirmed = false; // Participants can retrieve their Ether back once refunds are enabled. bool public refundsEnabled = false; // Owner of the contract. address public owner; // 4% fee for the development. uint256 public constant DEVELOPER_FEE_PERCENTAGE = 4; // Total number of collected fees. uint256 public collectedFees = 0; // Constant representing 100%. uint256 private constant PERCENTAGE_100 = 100; // Events to notify frontend. event Stake(address indexed staker, uint256 indexed countryID, uint256 amount); event WinnerAnnounced(uint256 winnerID); event WinnerConfirmed(uint256 winnerID); event Claim(address indexed staker, uint256 stakeAmount, uint256 claimAmount); event RefundsEnabled(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Initialize fields in the constructor. function Eurovision() public { owner = msg.sender; countryWinnerID = uint256(Countries.NONE); } // Stake on a specific country. function stake(uint256 countryID) external validCountry(countryID) payable { require(now <= STAKE_DEADLINE); require(!refundsEnabled); require(msg.value >= MIN_STAKE); address staker = msg.sender; uint256 weiAmount = msg.value; uint256 fee = weiAmount.mul(DEVELOPER_FEE_PERCENTAGE) / PERCENTAGE_100; uint256 actualStake = weiAmount.sub(fee); weiReceived[staker] = weiReceived[staker].add(actualStake); stakes[staker][countryID] = stakes[staker][countryID].add(actualStake); countryStats[countryID].amount = countryStats[countryID].amount.add(actualStake); if (stakes[staker][countryID] == actualStake) { countryStats[countryID].numberOfStakers++; } collectedFees = collectedFees.add(fee); totalPot = totalPot.add(actualStake); Stake(staker, countryID, actualStake); } // Get back all your Ether (fees are also refunded). function refund() external { require(canRefund()); require(!claimed[msg.sender]); address refunder = msg.sender; uint256 refundAmount = weiReceived[refunder].mul(PERCENTAGE_100) / (PERCENTAGE_100.sub(DEVELOPER_FEE_PERCENTAGE)) ; claimed[refunder] = true; if (collectedFees > 0) { collectedFees = 0; } refunder.transfer(refundAmount); Claim(refunder, refundAmount, refundAmount); } // Claim your reward if you guessed the winner correctly. function claimWinnings() external { require(winnerConfirmed); require(now <= CLAIM_DEADLINE); require(!refundsEnabled); require(!claimed[msg.sender]); address claimer = msg.sender; uint256 myStakesOnWinner = myStakesOnCountry(countryWinnerID); uint256 totalStakesOnWinner = countryStats[countryWinnerID].amount; uint256 reward = myStakesOnWinner.mul(totalPot) / totalStakesOnWinner; claimed[claimer] = true; claimer.transfer(reward); Claim(claimer, myStakesOnWinner, reward); } // Send the query to Oraclize to retrieve the winner ID. function queryWinner(string apiKey) external possibleToAnnounceWinner onlyOwner { require(now > STAKE_DEADLINE); if (now.add(24 hours) >= ANNOUNCE_WINNER_DEADLINE && countryWinnerID == uint256(Countries.NONE)) { attemptsToQueryInLast24Hours.add(1); lastQueryTime = now; } oraclize_query("computation", ["QmQ9PvNoKSRpbGduSbvyBHwVZQ97Pw7JYEnbTiLfcKHapE", apiKey]); } // Oraclize callback. Returns result from the computation datasource. function __callback(bytes32 myid, string result) { require(msg.sender == oraclize_cbAddress()); uint256 winnerID = parseInt(result); require(winnerID > 0); require(winnerID <= NUMBER_OF_COUNTRIES); countryWinnerID = winnerID; WinnerAnnounced(countryWinnerID); } // If the Oraclize didn&#39;t return the result in 30 mins during the last 24 hours, owner can announce the winner manually. function announceWinnerManually(uint256 winnerID) external validCountry(winnerID) possibleToAnnounceWinner onlyOwner { require(attemptsToQueryInLast24Hours >= MIN_NUMBER_OF_ATTEMPTS_TO_WAIT); require(now >= lastQueryTime.add(MIN_CALLBACK_WAIT_TIME)); countryWinnerID = winnerID; WinnerAnnounced(countryWinnerID); } // 2-step verification that the right winner was announced (minimize the probability of error). function confirmWinner() external possibleToAnnounceWinner onlyOwner { require(countryWinnerID != uint256(Countries.NONE)); winnerConfirmed = true; WinnerConfirmed(countryWinnerID); } // Fallback function. Owner can send some Ether to the contract. Ether is needed to call the Oraclize. function () external payable onlyOwner { } // Get total stakes amount and number of stakers for specific country. function getCountryStats(uint256 countryID) external view validCountry(countryID) returns(uint256 amount, uint256 numberOfStakers) { return (countryStats[countryID].amount, countryStats[countryID].numberOfStakers); } // Get my amount of stakes for a specific country. function myStakesOnCountry(uint256 countryID) public view validCountry(countryID) returns(uint256 myStake) { return stakes[msg.sender][countryID]; } // Get my total amount of Ether staked on all countries. function myTotalStakeAmount() public view returns(uint256 myStake) { return weiReceived[msg.sender]; } // Indicated if an address has already claimed the winnings/refunds. function alreadyClaimed() public view returns(bool hasClaimed) { return claimed[msg.sender]; } // Check if refunds are possible. function canRefund() public view returns(bool) { bool winnerNotAnnouncedInTime = (now > ANNOUNCE_WINNER_DEADLINE) && !winnerConfirmed; bool notExpired = (now <= CLAIM_DEADLINE); return (refundsEnabled || winnerNotAnnouncedInTime) && notExpired; } // In case of an emergency situation or other unexpected event an owner of the contract can explicitly enable refunds. function enableRefunds() external onlyOwner { require(!refundsEnabled); require(!winnerConfirmed); refundsEnabled = true; RefundsEnabled(); } // Only when all the winnings are supposed to be claimed, owner can receive the fees. function claimFees() external onlyOwner { require(now > CLAIM_DEADLINE); require(collectedFees > 0); uint256 amount = collectedFees; collectedFees = 0; owner.transfer(amount); } // Transfer ownership of the contract to the new address. function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; OwnershipTransferred(owner, newOwner); } // Free the memory when the contest ends and all the winnings/refunds are supposed to be claimed. function kill() external onlyOwner { require(now > CLAIM_DEADLINE); selfdestruct(owner); } // ID belongs to the list. modifier validCountry(uint256 countryID) { require(countryID > 0); require(countryID <= NUMBER_OF_COUNTRIES); _; } // Valid state to announce/confirm the winner. modifier possibleToAnnounceWinner() { require(now <= ANNOUNCE_WINNER_DEADLINE); require(!refundsEnabled); require(!winnerConfirmed); _; } // Only executable by an owner of the contract. modifier onlyOwner() { require(msg.sender == owner); _; } }
2-step verification that the right winner was announced (minimize the probability of error).
function confirmWinner() external possibleToAnnounceWinner onlyOwner { require(countryWinnerID != uint256(Countries.NONE)); winnerConfirmed = true; WinnerConfirmed(countryWinnerID); }
7,835,885
./full_match/1/0xFF9CF325bfA593f7dBDBd7a3e21966Ca53cf7d71/sources/contracts/artist/common/simple-minter/WildXYZMinterPresale.sol
Sets the group end time. Sets the given group end time. Only callable by admin. _groupId The group ID. Must be a valid group ID. _endTime The new end time of the group./
function setGroupEndTime(uint256 _groupId, uint256 _endTime) public virtual validGroup(_groupId) onlyAdmin { groups[_groupId].endTime = _endTime; }
3,214,322
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.7; // @TODO: Formatting library LibBytes { // @TODO: see if we can just set .length = function trimToSize(bytes memory b, uint newLen) internal pure { require(b.length > newLen, "BytesLib: only shrinking"); assembly { mstore(b, newLen) } } /***********************************| | Read Bytes Functions | |__________________________________*/ /** * @dev Reads a bytes32 value from a position in a byte array. * @param b Byte array containing a bytes32 value. * @param index Index in byte array of bytes32 value. * @return result bytes32 value from byte array. */ function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { // Arrays are prefixed by a 256 bit length parameter index += 32; require(b.length >= index, "BytesLib: length"); // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } } interface IERC1271Wallet { function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue); } library SignatureValidator { using LibBytes for bytes; enum SignatureMode { EIP712, EthSign, SmartWallet, Spoof } // bytes4(keccak256("isValidSignature(bytes32,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e; function recoverAddr(bytes32 hash, bytes memory sig) internal view returns (address) { return recoverAddrImpl(hash, sig, false); } function recoverAddrImpl(bytes32 hash, bytes memory sig, bool allowSpoofing) internal view returns (address) { require(sig.length >= 1, "SV_SIGLEN"); uint8 modeRaw; unchecked { modeRaw = uint8(sig[sig.length - 1]); } SignatureMode mode = SignatureMode(modeRaw); // {r}{s}{v}{mode} if (mode == SignatureMode.EIP712 || mode == SignatureMode.EthSign) { require(sig.length == 66, "SV_LEN"); bytes32 r = sig.readBytes32(0); bytes32 s = sig.readBytes32(32); uint8 v = uint8(sig[64]); // Hesitant about this check: seems like this is something that has no business being checked on-chain require(v == 27 || v == 28, "SV_INVALID_V"); if (mode == SignatureMode.EthSign) hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); address signer = ecrecover(hash, v, r, s); require(signer != address(0), "SV_ZERO_SIG"); return signer; // {sig}{verifier}{mode} } else if (mode == SignatureMode.SmartWallet) { // 32 bytes for the addr, 1 byte for the type = 33 require(sig.length > 33, "SV_LEN_WALLET"); uint newLen; unchecked { newLen = sig.length - 33; } IERC1271Wallet wallet = IERC1271Wallet(address(uint160(uint256(sig.readBytes32(newLen))))); sig.trimToSize(newLen); require(ERC1271_MAGICVALUE_BYTES32 == wallet.isValidSignature(hash, sig), "SV_WALLET_INVALID"); return address(wallet); // {address}{mode}; the spoof mode is used when simulating calls } else if (mode == SignatureMode.Spoof && allowSpoofing) { // This is safe cause it's specifically intended for spoofing sigs in simulation conditions, where tx.origin can be controlled // slither-disable-next-line tx-origin require(tx.origin == address(1), "SV_SPOOF_ORIGIN"); require(sig.length == 33, "SV_SPOOF_LEN"); sig.trimToSize(32); return abi.decode(sig, (address)); } else revert("SV_SIGMODE"); } } library MerkleProof { function isContained(bytes32 valueHash, bytes32[] memory proof, bytes32 root) internal pure returns (bool) { bytes32 cursor = valueHash; uint256 proofLen = proof.length; for (uint256 i = 0; i < proofLen; i++) { if (cursor < proof[i]) { cursor = keccak256(abi.encodePacked(cursor, proof[i])); } else { cursor = keccak256(abi.encodePacked(proof[i], cursor)); } } return cursor == root; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract WALLETToken { // Constants string public constant name = "Ambire Wallet"; string public constant symbol = "WALLET"; uint8 public constant decimals = 18; uint public constant MAX_SUPPLY = 1_000_000_000 * 1e18; // Mutable variables uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); event SupplyControllerChanged(address indexed prev, address indexed current); address public supplyController; constructor(address _supplyController) { supplyController = _supplyController; emit SupplyControllerChanged(address(0), _supplyController); } function balanceOf(address owner) external view returns (uint balance) { return balances[owner]; } function transfer(address to, uint amount) external returns (bool success) { balances[msg.sender] = balances[msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { balances[from] = balances[from] - amount; allowed[from][msg.sender] = allowed[from][msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) external returns (bool success) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) external view returns (uint remaining) { return allowed[owner][spender]; } // Supply control function innerMint(address owner, uint amount) internal { totalSupply = totalSupply + amount; require(totalSupply < MAX_SUPPLY, 'MAX_SUPPLY'); balances[owner] = balances[owner] + amount; // Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 emit Transfer(address(0), owner, amount); } function mint(address owner, uint amount) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); innerMint(owner, amount); } function changeSupplyController(address newSupplyController) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); // Emitting here does not follow checks-effects-interactions-logs, but it's safe anyway cause there are no external calls emit SupplyControllerChanged(supplyController, newSupplyController); supplyController = newSupplyController; } } interface IStakingPool { function enterTo(address recipient, uint amount) external; } contract WALLETSupplyController { event LogNewVesting(address indexed recipient, uint start, uint end, uint amountPerSec); event LogVestingUnset(address indexed recipient, uint end, uint amountPerSec); event LogMintVesting(address indexed recipient, uint amount); // solhint-disable-next-line var-name-mixedcase WALLETToken public immutable WALLET; mapping (address => bool) public hasGovernance; constructor(WALLETToken token, address initialGovernance) { hasGovernance[initialGovernance] = true; WALLET = token; } // Governance and supply controller function changeSupplyController(address newSupplyController) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); WALLET.changeSupplyController(newSupplyController); } function setGovernance(address addr, bool level) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // Sometimes we need to get someone to de-auth themselves, but // it's better to protect against bricking rather than have this functionality // we can burn conrtol by transferring control over to a contract that can't mint or by ypgrading the supply controller require(msg.sender != addr, "CANNOT_MODIFY_SELF"); hasGovernance[addr] = level; } // Vesting // Some addresses (eg StakingPools) are incentivized with a certain allowance of WALLET per year // Also used for linear vesting of early supporters, team, etc. // mapping of (addr => end => rate) => lastMintTime; mapping (address => mapping(uint => mapping(uint => uint))) public vestingLastMint; function setVesting(address recipient, uint start, uint end, uint amountPerSecond) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // no more than 10 WALLET per second; theoretical emission max should be ~8 WALLET require(amountPerSecond <= 10e18, "AMOUNT_TOO_LARGE"); require(start >= 1643695200, "START_TOO_LOW"); require(vestingLastMint[recipient][end][amountPerSecond] == 0, "VESTING_ALREADY_SET"); vestingLastMint[recipient][end][amountPerSecond] = start; emit LogNewVesting(recipient, start, end, amountPerSecond); } function unsetVesting(address recipient, uint end, uint amountPerSecond) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // AUDIT: Pending (unclaimed) vesting is lost here - this is intentional vestingLastMint[recipient][end][amountPerSecond] = 0; emit LogVestingUnset(recipient, end, amountPerSecond); } // vesting mechanism function mintableVesting(address addr, uint end, uint amountPerSecond) public view returns (uint) { uint lastMinted = vestingLastMint[addr][end][amountPerSecond]; if (lastMinted == 0) return 0; // solhint-disable-next-line not-rely-on-time if (block.timestamp > end) { require(end > lastMinted, "VESTING_OVER"); return (end - lastMinted) * amountPerSecond; } else { // this means we have not started yet // solhint-disable-next-line not-rely-on-time if (lastMinted > block.timestamp) return 0; // solhint-disable-next-line not-rely-on-time return (block.timestamp - lastMinted) * amountPerSecond; } } function mintVesting(address recipient, uint end, uint amountPerSecond) external { uint amount = mintableVesting(recipient, end, amountPerSecond); // solhint-disable-next-line not-rely-on-time vestingLastMint[recipient][end][amountPerSecond] = block.timestamp; WALLET.mint(recipient, amount); emit LogMintVesting(recipient, amount); } // // Rewards distribution // event LogUpdatePenaltyBps(uint newPenaltyBps); event LogClaimStaked(address indexed recipient, uint claimed); event LogClaimWithPenalty(address indexed recipient, uint received, uint burned); uint public immutable MAX_CLAIM_NODE = 80_000_000e18; bytes32 public lastRoot; mapping (address => uint) public claimed; uint public penaltyBps = 0; function setPenaltyBps(uint _penaltyBps) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); require(penaltyBps <= 10000, "BPS_IN_RANGE"); penaltyBps = _penaltyBps; emit LogUpdatePenaltyBps(_penaltyBps); } function setRoot(bytes32 newRoot) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); lastRoot = newRoot; } function claimWithRootUpdate( // claim() args uint totalRewardInTree, bytes32[] calldata proof, uint toBurnBps, IStakingPool stakingPool, // args for updating the root bytes32 newRoot, bytes calldata signature ) external { address signer = SignatureValidator.recoverAddrImpl(newRoot, signature, false); require(hasGovernance[signer], "NOT_GOVERNANCE"); lastRoot = newRoot; claim(totalRewardInTree, proof, toBurnBps, stakingPool); } // claim() has two modes, either receive the full amount as xWALLET (staked WALLET) or burn some (penaltyBps) and receive the rest immediately in $WALLET // toBurnBps is a safety parameter that serves two purposes: // 1) prevents griefing attacks/frontrunning where governance sets penalties higher before someone's claim() gets mined // 2) ensures that the sender really does have the intention to burn some of their tokens but receive the rest immediatey // set toBurnBps to 0 to receive the tokens as xWALLET, set it to the current penaltyBps to receive immediately // There is an edge case: when penaltyBps is set to 0, you pass 0 to receive everything immediately; this is intended function claim(uint totalRewardInTree, bytes32[] memory proof, uint toBurnBps, IStakingPool stakingPool) public { address recipient = msg.sender; require(totalRewardInTree <= MAX_CLAIM_NODE, "MAX_CLAIM_NODE"); require(lastRoot != bytes32(0), "EMPTY_ROOT"); // Check the merkle proof bytes32 leaf = keccak256(abi.encode(address(this), recipient, totalRewardInTree)); require(MerkleProof.isContained(leaf, proof, lastRoot), "LEAF_NOT_FOUND"); uint toClaim = totalRewardInTree - claimed[recipient]; claimed[recipient] = totalRewardInTree; if (toBurnBps == penaltyBps) { // Claiming in $WALLET directly: some tokens get burned immediately, but the rest go to you uint toBurn = (toClaim * penaltyBps) / 10000; uint toReceive = toClaim - toBurn; // AUDIT: We can check toReceive > 0 or toBurn > 0, but there's no point since in the most common path both will be non-zero WALLET.mint(recipient, toReceive); WALLET.mint(address(0), toBurn); emit LogClaimWithPenalty(recipient, toReceive, toBurn); } else if (toBurnBps == 0) { WALLET.mint(address(this), toClaim); if (WALLET.allowance(address(this), address(stakingPool)) < toClaim) { WALLET.approve(address(stakingPool), type(uint256).max); } stakingPool.enterTo(recipient, toClaim); emit LogClaimStaked(recipient, toClaim); } else { revert("INVALID_TOBURNBPS"); } } // In case funds get stuck function withdraw(IERC20 token, address to, uint256 tokenAmount) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // AUDIT: SafeERC20 or similar not needed; this is a trusted (governance only) method that doesn't modify internal accounting // so sucess/fail does not matter token.transfer(to, tokenAmount); } }
no more than 10 WALLET per second; theoretical emission max should be ~8 WALLET
function setVesting(address recipient, uint start, uint end, uint amountPerSecond) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); require(amountPerSecond <= 10e18, "AMOUNT_TOO_LARGE"); require(start >= 1643695200, "START_TOO_LOW"); require(vestingLastMint[recipient][end][amountPerSecond] == 0, "VESTING_ALREADY_SET"); vestingLastMint[recipient][end][amountPerSecond] = start; emit LogNewVesting(recipient, start, end, amountPerSecond); }
6,106,282
/** *Submitted for verification at Etherscan.io on 2022-04-24 */ //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's + operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's * operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. Note: this function uses a * revert opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers whenNotPaused and whenPaused, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by account. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by account. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a safeTransferFrom after the balance has been updated. To accept the transfer, this must return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a safeBatchTransferFrom after the balances have been updated. To accept the transfer(s), this must return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when value tokens of token type id are transferred from from to to by operator. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where operator, from and to are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when account grants or revokes permission to operator to transfer their tokens, according to * approved. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type id changes to value, if it is a non-programmatic URI. * * If an {URI} event was emitted for id, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that value will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type id owned by account. * * Requirements: * * - account cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - accounts and ids must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to operator to transfer the caller's tokens, according to approved, * * Emits an {ApprovalForAll} event. * * Requirements: * * - operator cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if operator is approved to transfer account's tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers amount tokens of token type id from from to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - If the caller is not from, it must be have been approved to spend from's tokens via {setApprovalForAll}. * - from must have a balance of tokens of type id of at least amount. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - ids and amounts must have the same length. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type id. * * If the {id} substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping for token ID that are not able to traded // For reasons mapping to uint8 instead of boolean // so 1 = false and 255 = true mapping (uint256 => uint8) tokenTradingStatus; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the {id} substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - account cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - accounts and ids must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(tokenTradingStatus[id] == 255, "Token is not tradeable!"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { for (uint256 i = 0; i < ids.length; ++i) { require(tokenTradingStatus[ids[i]] == 255, "Token is not tradeable!"); } require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers amount tokens of token type id from from to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - from must have a balance of tokens of type id of at least amount. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the {id} substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the https://token-cdn-domain/{id}.json URI would be * interpreted by clients as * https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates amount tokens of token type id, and assigns them to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - ids and amounts must have the same length. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys amount tokens of token type id from from * * Requirements: * * - from cannot be the zero address. * - from must have at least amount tokens of token type id. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - ids and amounts must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve operator to operate on all of owner tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the id and amount arrays will be 1. * * Calling conditions (for each id and amount pair): * * - When from and to are both non-zero, amount of from's tokens * of token type id will be transferred to to. * - When from is zero, amount tokens of token type id will be minted * for to. * - when to is zero, amount of from's tokens of token type id * will be burned. * - from and to are never both zero. * - ids and amounts have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155, Ownable { using SafeMath for uint256; mapping (uint256 => uint256) private _totalSupply; mapping (uint256 => uint256) private tokenSupplyCap; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 _id) public view virtual returns (uint256) { return _totalSupply[_id]; } function getTokenSupplyCap(uint256 _id) public view virtual returns (uint256) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return tokenSupplyCap[_id]; } function setTokenSupplyCap(uint256 _id, uint256 _newSupplyCap) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_newSupplyCap > tokenSupplyCap[_id], "New Supply Cap can only be greater than previous supply cap."); tokenSupplyCap[_id] = _newSupplyCap; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } //-------------END DEPENDENCIES------------------------// // File: MerkleProof.sol - OpenZeppelin Standard pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a 'leaf' can be proved to be a part of a Merkle tree * defined by 'root'. For this, a 'proof' must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from 'leaf' using 'proof'. A 'proof' is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: Allowlist.sol pragma solidity ^0.8.0; abstract contract Allowlist is Ownable { mapping(uint256 => bytes32) private merkleRoot; mapping(uint256 => bool) private allowlistMode; bool public onlyAllowlistMode = false; /** * @dev Get merkle root for specific token in collection * @param _id token id from collection */ function merkleRootForToken(uint256 _id) public view returns(bytes32) { return merkleRoot[_id]; } /** * @dev Update merkle root to reflect changes in Allowlist * @param _id token if for merkle root * @param _newMerkleRoot new merkle root to reflect most recent Allowlist */ function updateMerkleRoot(uint256 _id, bytes32 _newMerkleRoot) public onlyOwner { require(_newMerkleRoot != merkleRoot[_id], "Merkle root will be unchanged!"); merkleRoot[_id] = _newMerkleRoot; } /** * @dev Check the proof of an address if valid for merkle root * @param _address address to check for proof * @param _tokenId token id to check root of * @param _merkleProof Proof of the address to validate against root and leaf */ function isAllowlisted(address _address, uint256 _tokenId, bytes32[] calldata _merkleProof) public view returns(bool) { require(merkleRootForToken(_tokenId) != 0, "Merkle root is not set!"); bytes32 leaf = keccak256(abi.encodePacked(_address)); return MerkleProof.verify(_merkleProof, merkleRoot[_tokenId], leaf); } function inAllowlistMode(uint256 _id) public view returns (bool) { return allowlistMode[_id] == true; } function enableAllowlistOnlyMode(uint256 _id) public onlyOwner { allowlistMode[_id] = true; } function disableAllowlistOnlyMode(uint256 _id) public onlyOwner { allowlistMode[_id] = false; } } abstract contract Ramppable { address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ramppable { address[] public payableAddresses = [RAMPPADDRESS,0xe1c4bD0982a7459EF255f2FAaF1F0F79Ef721A16]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } /** * @dev Allows Rampp wallet to update its own reference as well as update * the address for the Rampp-owed payment split. Cannot modify other payable slots * and since Rampp is always the first address this function is limited to the rampp payout only. * @param _newAddress updated Rampp Address */ function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; } } // File: isFeeable.sol abstract contract isPriceable is Ownable { using SafeMath for uint256; mapping (uint256 => uint256) tokenPrice; function getPriceForToken(uint256 _id) public view returns(uint256) { return tokenPrice[_id]; } function setPriceForToken(uint256 _id, uint256 _feeInWei) public onlyOwner { tokenPrice[_id] = _feeInWei; } } // File: hasTransactionCap.sol abstract contract hasTransactionCap is Ownable { using SafeMath for uint256; mapping (uint256 => uint256) transactionCap; function getTransactionCapForToken(uint256 _id) public view returns(uint256) { return transactionCap[_id]; } function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyOwner { require(_transactionCap > 0, "Quantity must be more than zero"); transactionCap[_id] = _transactionCap; } function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) { return _qty <= transactionCap[_id]; } } // File: Closeable.sol abstract contract Closeable is Ownable { mapping (uint256 => bool) mintingOpen; function openMinting(uint256 _id) public onlyOwner { mintingOpen[_id] = true; } function closeMinting(uint256 _id) public onlyOwner { mintingOpen[_id] = false; } function isMintingOpen(uint256 _id) public view returns(bool) { return mintingOpen[_id] == true; } function setInitialMintingStatus(uint256 _id, bool _initStatus) internal { mintingOpen[_id] = _initStatus; } } // File: contracts/WlWtokenContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.2; contract WlWtokenContract is ERC1155, Ownable, Pausable, ERC1155Supply, Withdrawable, Closeable, isPriceable, hasTransactionCap, Allowlist { constructor() ERC1155('') {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 1; bytes private emptyBytes; uint256 public currentTokenID = 0; string public name = "WLW token"; string public symbol = "WLW"; mapping (uint256 => string) baseTokenURI; /** * @dev returns the URI for a specific token to show metadata on marketplaces * @param _id the maximum supply of tokens for this token */ function uri(uint256 _id) public override view returns (string memory) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return baseTokenURI[_id]; } function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/YJW8zgBiAxBoCsbTeV3Q/contract-metadata"; } /////////////// Admin Mint Functions function mintToAdmin(address _address, uint256 _id, uint256 _qty) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty > 0, "Minting quantity must be over 0"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); _mint(_address, _id, _qty, emptyBytes); } function mintManyAdmin(address[] memory addresses, uint256 _id, uint256 _qtyToEach) public onlyOwner { for(uint256 i=0; i < addresses.length; i++) { _mint(addresses[i], _id, _qtyToEach, emptyBytes); } } /////////////// Public Mint Functions /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _id token id of collection */ function mintTo(uint256 _id) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(totalSupply(_id).add(1) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, 1), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) == false, "Public minting is not enabled while contract is in allowlist only mode."); require(isMintingOpen(_id), "Minting for this token is not open"); _mint(msg.sender, _id, 1, emptyBytes); } /** * @dev Mints a number of tokens to a single address. * fee may or may not be required* * @param _id token id of collection * @param _qty amount to mint */ function mintToMultiple(uint256 _id, uint256 _qty) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty >= 1, "Must mint at least 1 token"); require(canMintQtyForTransaction(_id, _qty), "Cannot mint more than max mint per transaction"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, _qty), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) == false, "Public minting is not enabled while contract is in allowlist only mode."); require(isMintingOpen(_id), "Minting for this token is not open"); _mint(msg.sender, _id, _qty, emptyBytes); } ///////////// ALLOWLIST MINTING FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required - required to have proof of AL* * @param _id token id of collection * @param _merkleProof merkle proof tree for sender */ function mintToAL(uint256 _id, bytes32[] calldata _merkleProof) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(totalSupply(_id).add(1) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, 1), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) && isMintingOpen(_id), "Allowlist Mode and Minting must be enabled to mint"); require(isAllowlisted(msg.sender, _id, _merkleProof), "Address is not in Allowlist!"); _mint(msg.sender, _id, 1, emptyBytes); } /** * @dev Mints a number of tokens to a single address. * fee may or may not be required* * @param _id token id of collection * @param _qty amount to mint * @param _merkleProof merkle proof tree for sender */ function mintToMultipleAL(uint256 _id, uint256 _qty, bytes32[] calldata _merkleProof) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty >= 1, "Must mint at least 1 token"); require(canMintQtyForTransaction(_id, _qty), "Cannot mint more than max mint per transaction"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, _qty), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) && isMintingOpen(_id), "Allowlist Mode and Minting must be enabled to mint"); require(isAllowlisted(msg.sender, _id, _merkleProof), "Address is not in Allowlist!"); _mint(msg.sender, _id, _qty, emptyBytes); } /** * @dev Creates a new primary token for contract and gives creator first token * @param _tokenSupplyCap the maximum supply of tokens for this token * @param _tokenTransactionCap maximum amount of tokens one can buy per tx * @param _tokenFeeInWei payable fee per token * @param _isOpenDefaultStatus can token be publically minted once created * @param _allowTradingDefaultStatus is the token intially able to be transferred * @param _tokenURI the token URI to the metadata for this token */ function createToken( uint256 _tokenSupplyCap, uint256 _tokenTransactionCap, uint256 _tokenFeeInWei, bool _isOpenDefaultStatus, bool _allowTradingDefaultStatus, string memory _tokenURI ) public onlyOwner { require(_tokenSupplyCap > 0, "Token Supply Cap must be greater than zero."); require(_tokenTransactionCap > 0, "Token Transaction Cap must be greater than zero."); require(bytes(_tokenURI).length > 0, "Token URI cannot be an empty value"); uint256 tokenId = _getNextTokenID(); _mint(msg.sender, tokenId, 1, emptyBytes); baseTokenURI[tokenId] = _tokenURI; setTokenSupplyCap(tokenId, _tokenSupplyCap); setPriceForToken(tokenId, _tokenFeeInWei); setTransactionCapForToken(tokenId, _tokenTransactionCap); setInitialMintingStatus(tokenId, _isOpenDefaultStatus); tokenTradingStatus[tokenId] = _allowTradingDefaultStatus ? 255 : 1; _incrementTokenTypeId(); } /** * @dev pauses minting for all tokens in the contract */ function pause() public onlyOwner { _pause(); } /** * @dev unpauses minting for all tokens in the contract */ function unpause() public onlyOwner { _unpause(); } /** * @dev set the URI for a specific token on the contract * @param _id token id * @param _newTokenURI string for new metadata url (ex: ipfs://something) */ function setTokenURI(uint256 _id, string memory _newTokenURI) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); baseTokenURI[_id] = _newTokenURI; } /** * @dev calculates price for a token based on qty * @param _id token id * @param _qty desired amount to mint */ function getPrice(uint256 _id, uint256 _qty) public view returns (uint256) { require(_qty > 0, "Quantity must be more than zero"); return getPriceForToken(_id).mul(_qty); } /** * @dev prevent token from being transferred (aka soulbound) * @param tokenId token id */ function setTokenUntradeable(uint256 tokenId) public onlyOwner { require(tokenTradingStatus[tokenId] != 1, "Token ID is already untradeable!"); require(exists(tokenId), "Token ID does not exist!"); tokenTradingStatus[tokenId] = 1; } /** * @dev allow token from being transferred - the default mode * @param tokenId token id */ function setTokenTradeable(uint256 tokenId) public onlyOwner { require(tokenTradingStatus[tokenId] != 255, "Token ID is already tradeable!"); require(exists(tokenId), "Token ID does not exist!"); tokenTradingStatus[tokenId] = 255; } /** * @dev check if token id is tradeable * @param tokenId token id */ function isTokenTradeable(uint256 tokenId) public view returns (bool) { require(exists(tokenId), "Token ID does not exist!"); return tokenTradingStatus[tokenId] == 255; } function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function _getNextTokenID() private view returns (uint256) { return currentTokenID.add(1); } /** * @dev increments the value of currentTokenID */ function _incrementTokenTypeId() private { currentTokenID++; } } //*********************************************************************// //*********************************************************************// // Rampp v1.0.0 // // This smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT communities without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Rampp is not associated or affiliated with this project. // Twitter: @Rampp_ ---- rampp.xyz //*********************************************************************// //*********************************************************************//
Returns the rebuilt hash obtained by traversing a Merkle tree up from 'leaf' using 'proof'. A 'proof' is valid if and only if the rebuilt hash matches the root of the tree. When processing the proof, the pairs of leafs & pre-images are assumed to be sorted. _Available since v4.4._/ Hash(current computed hash + current element of the proof) Hash(current element of the proof + current computed hash)
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = _efficientHash(computedHash, proofElement); computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; }
2,142,156
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/introspection/ERC165.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interface/IERC721Metadata.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./ERC721.sol"; import "./interface/ILife.sol"; /** * @title NFTKEY Life collection contract */ contract Life is ILife, ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; constructor(string memory name_, string memory symbol_) public ERC721(name_, symbol_) {} uint256 public constant SALE_START_TIMESTAMP = 1616247000; uint256 public constant MAX_NFT_SUPPLY = 10000; mapping(address => uint256) private _pendingWithdrawals; mapping(uint256 => uint8[]) private _bioDNAById; mapping(bytes32 => bool) private _bioExistanceByHash; uint8 private _feeFraction = 1; uint8 private _feeBase = 100; mapping(uint256 => Listing) private _bioListedForSale; mapping(uint256 => Bid) private _bioWithBids; /** * @dev See {ILife-getBioDNA}. */ function getBioDNA(uint256 bioId) external view override returns (uint8[] memory) { return _bioDNAById[bioId]; } /** * @dev See {ILife-allBioDNAs}. */ function getBioDNAs(uint256 from, uint256 size) external view override returns (uint8[][] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many Bios"); uint8[][] memory bios = new uint8[][](size); for (uint256 i; i < size; i++) { bios[i] = _bioDNAById[i + from]; } return bios; } /** * @dev See {ILife-getBioPrice}. */ function getBioPrice() public view override returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply > 9900) { return 100000000000000000000; // 9901 - 10000 100 BNB } else if (currentSupply > 9500) { return 20000000000000000000; // 9501 - 9900 20 BNB } else if (currentSupply > 8500) { return 10000000000000000000; // 8501 - 9500 10 BNB } else if (currentSupply > 4500) { return 8000000000000000000; // 4501 - 8500 8 BNB } else if (currentSupply > 2500) { return 6000000000000000000; // 2501 - 4500 6 BNB } else if (currentSupply > 1000) { return 4000000000000000000; // 1001 - 2500 4 BNB } else if (currentSupply > 100) { return 2000000000000000000; // 101 - 1000 2 BNB } else { return 1000000000000000000; // 0 - 100 1 BNB } } /** * @dev See {ILife-isBioExist}. */ function isBioExist(uint8[] memory bioDNA) external view override returns (bool) { bytes32 bioHashOriginal = keccak256(abi.encodePacked(bioDNA)); return _bioExistanceByHash[bioHashOriginal]; } /** * @dev See {ILife-mintBio}. */ function mintBio(uint8[] memory bioDNA) external payable override { // Bio RLE require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(totalSupply().add(1) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getBioPrice() == msg.value, "Ether value sent is not correct"); bytes32 bioHash = keccak256(abi.encodePacked(bioDNA)); require(!_bioExistanceByHash[bioHash], "Bio already existed"); uint256 activeCellCount = 0; uint256 totalCellCount = 0; for (uint8 i = 0; i < bioDNA.length; i++) { totalCellCount = totalCellCount.add(bioDNA[i]); if (i % 2 == 1) { activeCellCount = activeCellCount.add(bioDNA[i]); } } require(totalCellCount <= 289, "Total cell count should be smaller than 289"); require( activeCellCount >= 5 && activeCellCount <= 48, "Active cell count of Bio is not allowed" ); uint256 mintIndex = totalSupply(); _bioExistanceByHash[bioHash] = true; _bioDNAById[mintIndex] = bioDNA; _safeMint(msg.sender, mintIndex); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(msg.value); emit BioMinted(mintIndex, msg.sender, bioDNA, bioHash); } modifier saleEnded() { require(totalSupply() >= MAX_NFT_SUPPLY, "Bio sale still going"); _; } modifier bioExist(uint256 bioId) { require(bioId < totalSupply(), "Bio doesn't exist"); _; } modifier isBioOwner(uint256 bioId) { require(ownerOf(bioId) == msg.sender, "Not the owner of this Bio"); _; } /** * @dev See {ILife-getBioListing}. */ function getBioListing(uint256 bioId) external view override returns (Listing memory) { return _bioListedForSale[bioId]; } /** * @dev See {ILife-getListings}. */ function getBioListings(uint256 from, uint256 size) external view override returns (Listing[] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many listings"); Listing[] memory listings = new Listing[](size); for (uint256 i; i < size; i++) { listings[i] = _bioListedForSale[i + from]; } return listings; } /** * @dev See {ILife-getBioBid}. */ function getBioBid(uint256 bioId) external view override returns (Bid memory) { return _bioWithBids[bioId]; } /** * @dev See {ILife-getBioBids}. */ function getBioBids(uint256 from, uint256 size) external view override returns (Bid[] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many bids"); Bid[] memory bids = new Bid[](size); for (uint256 i; i < totalSupply(); i++) { bids[i] = _bioWithBids[i + from]; } return bids; } /** * @dev See {ILife-listBioForSale}. */ function listBioForSale(uint256 bioId, uint256 minValue) external override saleEnded bioExist(bioId) isBioOwner(bioId) { _bioListedForSale[bioId] = Listing( true, bioId, msg.sender, minValue, address(0), block.timestamp ); emit BioListed(bioId, minValue, msg.sender, address(0)); } /** * @dev See {ILife-listBioForSaleToAddress}. */ function listBioForSaleToAddress( uint256 bioId, uint256 minValue, address toAddress ) external override saleEnded bioExist(bioId) isBioOwner(bioId) { _bioListedForSale[bioId] = Listing( true, bioId, msg.sender, minValue, toAddress, block.timestamp ); emit BioListed(bioId, minValue, msg.sender, toAddress); } function _delistBio(uint256 bioId) private saleEnded bioExist(bioId) { emit BioDelisted(bioId, _bioListedForSale[bioId].seller); delete _bioListedForSale[bioId]; } function _removeBid(uint256 bioId) private saleEnded bioExist(bioId) { emit BioBidRemoved(bioId, _bioWithBids[bioId].bidder); delete _bioWithBids[bioId]; } /** * @dev See {ILife-delistBio}. */ function delistBio(uint256 bioId) external override isBioOwner(bioId) { require(_bioListedForSale[bioId].isForSale, "Bio is not for sale"); _delistBio(bioId); } /** * @dev Return fund if it's not a contract, else add it to pending withdrawals * @param receiver Address to receive value * @param value value to send */ function _sendValue(address receiver, uint256 value) private { if (receiver.isContract() && receiver != msg.sender) { _pendingWithdrawals[receiver] = value; } else { Address.sendValue(payable(receiver), value); } } /** * @dev See {ILife-buyBio}. */ function buyBio(uint256 bioId) external payable override saleEnded bioExist(bioId) nonReentrant { Listing memory listing = _bioListedForSale[bioId]; require(listing.isForSale, "Bio is not for sale"); require( listing.onlySellTo == address(0) || listing.onlySellTo == msg.sender, "Bio is not selling to this address" ); require(ownerOf(bioId) == listing.seller, "This seller is not the owner"); require(msg.sender != ownerOf(bioId), "This Bio belongs to this address"); uint256 fees = listing.minValue.mul(_feeFraction).div(_feeBase); require( msg.value >= listing.minValue + fees, "The value send is below sale price plus fees" ); uint256 valueWithoutFees = msg.value.sub(fees); _sendValue(ownerOf(bioId), valueWithoutFees); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(fees); emit BioBought(bioId, valueWithoutFees, listing.seller, msg.sender); _safeTransfer(ownerOf(bioId), msg.sender, bioId, ""); _delistBio(bioId); Bid memory existingBid = _bioWithBids[bioId]; if (existingBid.bidder == msg.sender) { _sendValue(msg.sender, existingBid.value); _removeBid(bioId); } } /** * @dev See {ILife-enterBidForBio}. */ function enterBidForBio(uint256 bioId) external payable override saleEnded bioExist(bioId) nonReentrant { require(ownerOf(bioId) != address(0), "This Bio has been burnt"); require(ownerOf(bioId) != msg.sender, "Owner of Bio doesn't need to bid"); require(msg.value != 0, "The bid price is too low"); Bid memory existingBid = _bioWithBids[bioId]; require(msg.value > existingBid.value, "The bid price is no higher than existing one"); if (existingBid.value > 0) { _sendValue(existingBid.bidder, existingBid.value); } _bioWithBids[bioId] = Bid(true, bioId, msg.sender, msg.value, block.timestamp); emit BioBidEntered(bioId, msg.value, msg.sender); } /** * @dev See {ILife-acceptBidForBio}. */ function acceptBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) isBioOwner(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.hasBid && existingBid.value > 0, "This Bio doesn't have a valid bid"); uint256 fees = existingBid.value.mul(_feeFraction).div(_feeBase + _feeFraction); uint256 bioValue = existingBid.value.sub(fees); _sendValue(msg.sender, bioValue); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(fees); _safeTransfer(msg.sender, existingBid.bidder, bioId, ""); emit BioBidAccepted(bioId, bioValue, msg.sender, existingBid.bidder); _removeBid(bioId); if (_bioListedForSale[bioId].isForSale) { _delistBio(bioId); } } /** * @dev See {ILife-withdrawBidForBio}. */ function withdrawBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.bidder == msg.sender, "This address doesn't have active bid"); _sendValue(msg.sender, existingBid.value); emit BioBidWithdrawn(bioId, existingBid.value, existingBid.bidder); _removeBid(bioId); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 bioId ) public override nonReentrant { require( _isApprovedOrOwner(_msgSender(), bioId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, bioId); if (_bioListedForSale[bioId].seller == from) { _delistBio(bioId); } if (_bioWithBids[bioId].bidder == to) { _sendValue(_bioWithBids[bioId].bidder, _bioWithBids[bioId].value); _removeBid(bioId); } } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 bioId ) public override { safeTransferFrom(from, to, bioId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 bioId, bytes memory _data ) public override nonReentrant { require( _isApprovedOrOwner(_msgSender(), bioId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, bioId, _data); if (_bioListedForSale[bioId].seller == from) { _delistBio(bioId); } if (_bioWithBids[bioId].bidder == to) { _sendValue(_bioWithBids[bioId].bidder, _bioWithBids[bioId].value); _removeBid(bioId); } } /** * @dev See {ILife-serviceFee}. */ function serviceFee() external view override returns (uint8, uint8) { return (_feeFraction, _feeBase); } /** * @dev See {ILife-pendingWithdrawals}. */ function pendingWithdrawals(address toAddress) external view override returns (uint256) { return _pendingWithdrawals[toAddress]; } /** * @dev See {ILife-withdraw}. */ function withdraw() external override nonReentrant { require(_pendingWithdrawals[msg.sender] > 0, "There is nothing to withdraw"); _sendValue(msg.sender, _pendingWithdrawals[msg.sender]); _pendingWithdrawals[msg.sender] = 0; } /** * @dev Change withdrawal fee percentage. * If 1%, then input (1,100) * If 0.5%, then input (5,1000) * @param feeFraction_ Fraction of withdrawal fee based on feeBase_ * @param feeBase_ Fraction of withdrawal fee base */ function changeSeriveFee(uint8 feeFraction_, uint8 feeBase_) external onlyOwner { require(feeFraction_ <= feeBase_, "Fee fraction exceeded base."); uint256 percentage = (feeFraction_ * 1000) / feeBase_; require(percentage <= 25, "Attempt to set percentage higher than 2.5%."); _feeFraction = feeFraction_; _feeBase = feeBase_; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12; pragma experimental ABIEncoderV2; /** * @title NFTKEY Life interface */ interface ILife { struct Listing { bool isForSale; uint256 bioId; address seller; uint256 minValue; address onlySellTo; uint256 timestamp; } struct Bid { bool hasBid; uint256 bioId; address bidder; uint256 value; uint256 timestamp; } event BioMinted(uint256 indexed bioId, address indexed owner, uint8[] bioDNA, bytes32 bioHash); event BioListed( uint256 indexed bioId, uint256 minValue, address indexed fromAddress, address indexed toAddress ); event BioDelisted(uint256 indexed bioId, address indexed fromAddress); event BioBidEntered(uint256 indexed bioId, uint256 value, address indexed fromAddress); event BioBidWithdrawn(uint256 indexed bioId, uint256 value, address indexed fromAddress); event BioBidRemoved(uint256 indexed bioId, address indexed fromAddress); event BioBought( uint256 indexed bioId, uint256 value, address indexed fromAddress, address indexed toAddress ); event BioBidAccepted( uint256 indexed bioId, uint256 value, address indexed fromAddress, address indexed toAddress ); /** * @dev Gets DNA encoding of a Bio by token Id * @param bioId Bio token Id * @return Bio DNA encoding */ function getBioDNA(uint256 bioId) external view returns (uint8[] memory); /** * @dev Gets DNA encoding of a Bios * @param from From Bio id * @param size Query size * @return Bio DNAs */ function getBioDNAs(uint256 from, uint256 size) external view returns (uint8[][] memory); /** * @dev Gets current Bio Price * @return Current Bio Price */ function getBioPrice() external view returns (uint256); /** * @dev Check if a Bio is already minted or not * @param bioDNA Bio DNA encoding * @return If Bio exist, or if similar Bio exist */ function isBioExist(uint8[] memory bioDNA) external view returns (bool); /** * @dev Mint Bio * @param bioDNA Bio DNA encoding */ function mintBio(uint8[] memory bioDNA) external payable; /** * @dev Get Bio listing information * @param bioId Bio token id * @return Bio Listing detail */ function getBioListing(uint256 bioId) external view returns (Listing memory); /** * @dev Get Bio listings * @param from From Bio id * @param size Query size * @return Bio Listings */ function getBioListings(uint256 from, uint256 size) external view returns (Listing[] memory); /** * @dev Get Bio bid information * @param bioId Bio token id * @return Bio bid detail */ function getBioBid(uint256 bioId) external view returns (Bid memory); /** * @dev Get Bio bids * @param from From Bio id * @param size Query size * @return Bio bids */ function getBioBids(uint256 from, uint256 size) external view returns (Bid[] memory); /** * @dev List a Bio for sale * @param bioId Bio token id * @param minValue Bio minimum value */ function listBioForSale(uint256 bioId, uint256 minValue) external; /** * @dev List a Bio for sale to a certain address * @param bioId Bio token id * @param minValue Bio minimum value * @param toAddress Address to sell this Bio to */ function listBioForSaleToAddress( uint256 bioId, uint256 minValue, address toAddress ) external; /** * @dev Delist a Bio * @param bioId Bio token id */ function delistBio(uint256 bioId) external; /** * @dev Buy a Bio * @param bioId Bio token id */ function buyBio(uint256 bioId) external payable; /** * @dev Put bid on a Bio * @param bioId Bio token id */ function enterBidForBio(uint256 bioId) external payable; /** * @dev Accept s bid for a Bio * @param bioId Bio token id */ function acceptBidForBio(uint256 bioId) external; /** * @dev Withdraw s bid for a Bio * @param bioId Bio token id */ function withdrawBidForBio(uint256 bioId) external; /** * @dev Returns service fee. * @return The first value is fraction, the second one is fraction base */ function serviceFee() external view returns (uint8, uint8); /** * @dev Get pending withdrawals * @param toAddress Address to check withdrawals */ function pendingWithdrawals(address toAddress) external view returns (uint256); /** * @dev Withdraw ether from this contract */ function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); }
6,268,124
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts\common\Base.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Base is Initializable, Context, Ownable { address constant ZERO_ADDRESS = address(0); function initialize() public initializer { Ownable.initialize(_msgSender()); } } // File: contracts\core\ModuleNames.sol pragma solidity ^0.5.12; /** * @dev List of module names */ contract ModuleNames { // Pool Modules string internal constant MODULE_ACCESS = "access"; string internal constant MODULE_SAVINGS = "savings"; string internal constant MODULE_INVESTING = "investing"; string internal constant MODULE_STAKING_AKRO = "staking"; string internal constant MODULE_STAKING_ADEL = "stakingAdel"; string internal constant MODULE_DCA = "dca"; string internal constant MODULE_REWARD = "reward"; string internal constant MODULE_REWARD_DISTR = "rewardDistributions"; string internal constant MODULE_VAULT = "vault"; // Pool tokens string internal constant TOKEN_AKRO = "akro"; string internal constant TOKEN_ADEL = "adel"; // External Modules (used to store addresses of external contracts) string internal constant CONTRACT_RAY = "ray"; } // File: contracts\common\Module.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Module is Base, ModuleNames { event PoolAddressChanged(address newPool); address public pool; function initialize(address _pool) public initializer { Base.initialize(); setPool(_pool); } function setPool(address _pool) public onlyOwner { require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero"); pool = _pool; emit PoolAddressChanged(_pool); } function getModuleAddress(string memory module) public view returns(address){ require(pool != ZERO_ADDRESS, "Module: no pool"); (bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module)); //Forward error from Pool contract if (!success) assembly { revert(add(result, 32), result) } address moduleAddress = abi.decode(result, (address)); // string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); // require(moduleAddress != ZERO_ADDRESS, error); require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress; } } // File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\modules\defi\DefiOperatorRole.sol pragma solidity ^0.5.12; contract DefiOperatorRole is Initializable, Context { using Roles for Roles.Role; event DefiOperatorAdded(address indexed account); event DefiOperatorRemoved(address indexed account); Roles.Role private _operators; function initialize(address sender) public initializer { if (!isDefiOperator(sender)) { _addDefiOperator(sender); } } modifier onlyDefiOperator() { require(isDefiOperator(_msgSender()), "DefiOperatorRole: caller does not have the DefiOperator role"); _; } function addDefiOperator(address account) public onlyDefiOperator { _addDefiOperator(account); } function renounceDefiOperator() public { _removeDefiOperator(_msgSender()); } function isDefiOperator(address account) public view returns (bool) { return _operators.has(account); } function _addDefiOperator(address account) internal { _operators.add(account); emit DefiOperatorAdded(account); } function _removeDefiOperator(address account) internal { _operators.remove(account); emit DefiOperatorRemoved(account); } } // File: contracts\interfaces\defi\IDefiStrategy.sol pragma solidity ^0.5.12; contract IDefiStrategy { /** * @notice Transfer tokens from sender to DeFi protocol * @param token Address of token * @param amount Value of token to deposit * @return new balances of each token */ function handleDeposit(address token, uint256 amount) external; function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external; function withdraw(address beneficiary, address token, uint256 amount) external; function withdraw(address beneficiary, uint256[] calldata amounts) external; function setVault(address _vault) external; function normalizedBalance() external returns(uint256); function balanceOf(address token) external returns(uint256); function balanceOfAll() external returns(uint256[] memory balances); function getStrategyId() external view returns(string memory); } // File: contracts\interfaces\defi\IStrategyCurveFiSwapCrv.sol pragma solidity ^0.5.12; interface IStrategyCurveFiSwapCrv { event CrvClaimed(string indexed id, address strategy, uint256 amount); function curveFiTokenBalance() external view returns(uint256); function performStrategyStep1() external; function performStrategyStep2(bytes calldata _data, address _token) external; } // File: contracts\interfaces\defi\IVaultProtocol.sol pragma solidity ^0.5.12; //solhint-disable func-order contract IVaultProtocol { event DepositToVault(address indexed _user, address indexed _token, uint256 _amount); event WithdrawFromVault(address indexed _user, address indexed _token, uint256 _amount); event WithdrawRequestCreated(address indexed _user, address indexed _token, uint256 _amount); event DepositByOperator(uint256 _amount); event WithdrawByOperator(uint256 _amount); event WithdrawRequestsResolved(uint256 _totalDeposit, uint256 _totalWithdraw); event StrategyRegistered(address indexed _vault, address indexed _strategy, string _id); event Claimed(address indexed _vault, address indexed _user, address _token, uint256 _amount); event DepositsCleared(address indexed _vault); event RequestsCleared(address indexed _vault); function registerStrategy(address _strategy) external; function depositToVault(address _user, address _token, uint256 _amount) external; function depositToVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function withdrawFromVault(address _user, address _token, uint256 _amount) external; function withdrawFromVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function operatorAction(address _strategy) external returns(uint256, uint256); function operatorActionOneCoin(address _strategy, address _token) external returns(uint256, uint256); function clearOnHoldDeposits() external; function clearWithdrawRequests() external; function setRemainder(uint256 _amount, uint256 _index) external; function quickWithdraw(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function quickWithdrawStrategy() external view returns(address); function claimRequested(address _user) external; function normalizedBalance() external returns(uint256); function normalizedBalance(address _strategy) external returns(uint256); function normalizedVaultBalance() external view returns(uint256); function supportedTokens() external view returns(address[] memory); function supportedTokensCount() external view returns(uint256); function isStrategyRegistered(address _strategy) external view returns(bool); function registeredStrategies() external view returns(address[] memory); function isTokenRegistered(address _token) external view returns (bool); function tokenRegisteredInd(address _token) external view returns(uint256); function totalClaimableAmount(address _token) external view returns (uint256); function claimableAmount(address _user, address _token) external view returns (uint256); function amountOnHold(address _user, address _token) external view returns (uint256); function amountRequested(address _user, address _token) external view returns (uint256); } // File: contracts\interfaces\defi\ICurveFiDeposit.sol pragma solidity ^0.5.12; contract ICurveFiDeposit { function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount) external; function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust) external; function withdraw_donated_dust() external; function coins(int128 i) external view returns (address); function underlying_coins (int128 i) external view returns (address); function curve() external view returns (address); function token() external view returns (address); function calc_withdraw_one_coin (uint256 _token_amount, int128 i) external view returns (uint256); } // File: contracts\interfaces\defi\ICurveFiDeposit_Y.sol pragma solidity ^0.5.12; contract ICurveFiDeposit_Y { function add_liquidity (uint256[4] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity (uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance (uint256[4] calldata uamounts, uint256 max_burn_amount) external; } // File: contracts\interfaces\defi\ICurveFiLiquidityGauge.sol pragma solidity ^0.5.16; interface ICurveFiLiquidityGauge { //Addresses of tokens function lp_token() external returns(address); function crv_token() external returns(address); //Work with LP tokens function balanceOf(address addr) external view returns (uint256); function deposit(uint256 _value) external; function withdraw(uint256 _value) external; //Work with CRV function claimable_tokens(address addr) external returns (uint256); function minter() external view returns(address); //use minter().mint(gauge_addr) to claim CRV function integrate_fraction(address _for) external returns(uint256); function user_checkpoint(address _for) external returns(bool); } // File: contracts\interfaces\defi\ICurveFiMinter.sol pragma solidity ^0.5.16; interface ICurveFiMinter { function mint(address gauge_addr) external; function mint_for(address gauge_addr, address _for) external; function minted(address _for, address gauge_addr) external returns(uint256); } // File: contracts\interfaces\defi\ICurveFiSwap.sol pragma solidity ^0.5.12; interface ICurveFiSwap { function balances(int128 i) external view returns(uint256); function A() external view returns(uint256); function fee() external view returns(uint256); function coins(int128 i) external view returns (address); } // File: contracts\interfaces\defi\IDexag.sol pragma solidity ^0.5.12; /** * Interfce for Dexag Proxy * https://github.com/ConcourseOpen/DEXAG-Proxy/blob/master/contracts/DexTradingWithCollection.sol */ interface IDexag { function approvalHandler() external returns(address); function trade( address from, address to, uint256 fromAmount, address[] calldata exchanges, address[] calldata approvals, bytes calldata data, uint256[] calldata offsets, uint256[] calldata etherValues, uint256 limitAmount, uint256 tradeType ) external payable; } // File: contracts\interfaces\defi\IYErc20.sol pragma solidity ^0.5.12; //solhint-disable func-order contract IYErc20 { //ERC20 functions function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); //yToken functions function deposit(uint256 amount) external; function withdraw(uint256 shares) external; function getPricePerFullShare() external view returns (uint256); function token() external returns(address); } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } // File: contracts\utils\CalcUtils.sol pragma solidity ^0.5.12; library CalcUtils { using SafeMath for uint256; function normalizeAmount(address coin, uint256 amount) internal view returns(uint256) { uint8 decimals = ERC20Detailed(coin).decimals(); if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.div(uint256(10)**(decimals-18)); } else if (decimals < 18) { return amount.mul(uint256(10)**(18 - decimals)); } } function denormalizeAmount(address coin, uint256 amount) internal view returns(uint256) { uint256 decimals = ERC20Detailed(coin).decimals(); if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.mul(uint256(10)**(decimals-18)); } else if (decimals < 18) { return amount.div(uint256(10)**(18 - decimals)); } } } // File: contracts\modules\defi\CurveFiStablecoinStrategy.sol pragma solidity ^0.5.12; contract CurveFiStablecoinStrategy is Module, IDefiStrategy, IStrategyCurveFiSwapCrv, DefiOperatorRole { using SafeMath for uint256; using SafeERC20 for IERC20; struct PriceData { uint256 price; uint256 lastUpdateBlock; } address public vault; ICurveFiDeposit public curveFiDeposit; IERC20 public curveFiToken; ICurveFiLiquidityGauge public curveFiLPGauge; ICurveFiSwap public curveFiSwap; ICurveFiMinter public curveFiMinter; uint256 public slippageMultiplier; address public crvToken; address public dexagProxy; address public dexagApproveHandler; string internal strategyId; mapping(address=>PriceData) internal yPricePerFullShare; //Register stablecoins contracts addresses function initialize(address _pool, string memory _strategyId) public initializer { Module.initialize(_pool); DefiOperatorRole.initialize(_msgSender()); slippageMultiplier = 1.01*1e18; strategyId = _strategyId; } function setProtocol(address _depositContract, address _liquidityGauge, address _curveFiMinter, address _dexagProxy) public onlyDefiOperator { require(_depositContract != address(0), "Incorrect deposit contract address"); curveFiDeposit = ICurveFiDeposit(_depositContract); curveFiLPGauge = ICurveFiLiquidityGauge(_liquidityGauge); curveFiMinter = ICurveFiMinter(_curveFiMinter); curveFiSwap = ICurveFiSwap(curveFiDeposit.curve()); curveFiToken = IERC20(curveFiDeposit.token()); address lpToken = curveFiLPGauge.lp_token(); require(lpToken == address(curveFiToken), "CurveFiProtocol: LP tokens do not match"); crvToken = curveFiLPGauge.crv_token(); dexagProxy = _dexagProxy; dexagApproveHandler = IDexag(_dexagProxy).approvalHandler(); } function setVault(address _vault) public onlyDefiOperator { vault = _vault; } function setDexagProxy(address _dexagProxy) public onlyDefiOperator { dexagProxy = _dexagProxy; dexagApproveHandler = IDexag(_dexagProxy).approvalHandler(); } function handleDeposit(address token, uint256 amount) public onlyDefiOperator { uint256 nTokens = IVaultProtocol(vault).supportedTokensCount(); uint256[] memory amounts = new uint256[](nTokens); uint256 ind = IVaultProtocol(vault).tokenRegisteredInd(token); for (uint256 i=0; i < nTokens; i++) { amounts[i] = uint256(0); } IERC20(token).safeTransferFrom(vault, address(this), amount); IERC20(token).safeApprove(address(curveFiDeposit), amount); amounts[ind] = amount; ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0); //Stake Curve LP-token uint256 cftBalance = curveFiToken.balanceOf(address(this)); curveFiToken.safeApprove(address(curveFiLPGauge), cftBalance); curveFiLPGauge.deposit(cftBalance); } function handleDeposit(address[] memory tokens, uint256[] memory amounts) public onlyDefiOperator { require(tokens.length == amounts.length, "Count of tokens does not match count of amounts"); require(amounts.length == IVaultProtocol(vault).supportedTokensCount(), "Amounts count does not match registered tokens"); for (uint256 i=0; i < tokens.length; i++) { IERC20(tokens[i]).safeTransferFrom(vault, address(this), amounts[i]); IERC20(tokens[i]).safeApprove(address(curveFiDeposit), amounts[i]); } //Check for sufficient amounts on the Vault balances is checked in the WithdrawOperator() //Correct amounts are also set in WithdrawOperator() //Deposit stablecoins into the protocol ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0); //Stake Curve LP-token uint256 cftBalance = curveFiToken.balanceOf(address(this)); curveFiToken.safeApprove(address(curveFiLPGauge), cftBalance); curveFiLPGauge.deposit(cftBalance); } function withdraw(address beneficiary, address token, uint256 amount) public onlyDefiOperator { uint256 tokenIdx = IVaultProtocol(vault).tokenRegisteredInd(token); //All withdrawn tokens are marked as claimable, so anyway we need to withdraw from the protocol // count shares for proportional withdraw uint256 nAmount = CalcUtils.normalizeAmount(token, amount); uint256 nBalance = normalizedBalance(); uint256 poolShares = curveFiTokenBalance(); uint256 withdrawShares = poolShares.mul(nAmount).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw //Unstake Curve LP-token curveFiLPGauge.withdraw(withdrawShares); IERC20(curveFiToken).safeApprove(address(curveFiDeposit), withdrawShares); curveFiDeposit.remove_liquidity_one_coin(withdrawShares, int128(tokenIdx), amount, false); //DONATE_DUST - false IERC20(token).safeTransfer(beneficiary, amount); } function withdraw(address beneficiary, uint256[] memory amounts) public onlyDefiOperator { address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens(); require(amounts.length == registeredVaultTokens.length, "Wrong amounts array length"); //All withdrawn tokens are marked as claimable, so anyway we need to withdraw from the protocol uint256 nWithdraw; uint256 i; for (i = 0; i < registeredVaultTokens.length; i++) { address tkn = registeredVaultTokens[i]; nWithdraw = nWithdraw.add(CalcUtils.normalizeAmount(tkn, amounts[i])); } uint256 nBalance = normalizedBalance(); uint256 poolShares = curveFiTokenBalance(); uint256 withdrawShares = poolShares.mul(nWithdraw).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw //Unstake Curve LP-token curveFiLPGauge.withdraw(withdrawShares); IERC20(curveFiToken).safeApprove(address(curveFiDeposit), withdrawShares); ICurveFiDeposit_Y(address(curveFiDeposit)).remove_liquidity_imbalance(convertArray(amounts), withdrawShares); for (i = 0; i < registeredVaultTokens.length; i++){ IERC20 lToken = IERC20(registeredVaultTokens[i]); uint256 lBalance = lToken.balanceOf(address(this)); uint256 lAmount = (lBalance <= amounts[i])?lBalance:amounts[i]; // Rounding may prevent Curve.Fi to return exactly requested amount lToken.safeTransfer(beneficiary, lAmount); } } /** * @notice Operator should call this to receive CRV from curve */ function performStrategyStep1() external onlyDefiOperator { claimRewardsFromProtocol(); uint256 crvAmount = IERC20(crvToken).balanceOf(address(this)); emit CrvClaimed(strategyId, address(this), crvAmount); } /** * @notice Operator should call this to exchange CRV to DAI */ function performStrategyStep2(bytes calldata dexagSwapData, address swapStablecoin) external onlyDefiOperator { uint256 crvAmount = IERC20(crvToken).balanceOf(address(this)); IERC20(crvToken).safeApprove(dexagApproveHandler, crvAmount); (bool success, bytes memory result) = dexagProxy.call(dexagSwapData); if(!success) assembly { revert(add(result,32), result) //Reverts with same revert reason } //new dai tokens will be transferred to the Vault, they will be deposited by the operator on the next round //new LP tokens will be distributed automatically after the operator action uint256 amount = IERC20(swapStablecoin).balanceOf(address(this)); IERC20(swapStablecoin).safeTransfer(vault, amount); } function curveFiTokenBalance() public view returns(uint256) { uint256 notStaked = curveFiToken.balanceOf(address(this)); uint256 staked = curveFiLPGauge.balanceOf(address(this)); return notStaked.add(staked); } function claimRewardsFromProtocol() internal { curveFiMinter.mint_for(address(curveFiLPGauge), address(this)); } function balanceOf(address token) public returns(uint256) { uint256 tokenIdx = getTokenIndex(token); uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = curveFiToken.totalSupply(); uint256 yTokenCurveFiBalance = curveFiSwap.balances(int128(tokenIdx)); uint256 yTokenShares = yTokenCurveFiBalance.mul(cfBalance).div(cfTotalSupply); uint256 tokenBalance = getPricePerFullShare(curveFiSwap.coins(int128(tokenIdx))).mul(yTokenShares).div(1e18); //getPricePerFullShare() returns balance of underlying token multiplied by 1e18 return tokenBalance; } function balanceOfAll() public returns(uint256[] memory balances) { uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = curveFiToken.totalSupply(); uint256 nTokens = IVaultProtocol(vault).supportedTokensCount(); require(cfTotalSupply > 0, "No Curve pool tokens minted"); balances = new uint256[](nTokens); uint256 ycfBalance; for (uint256 i=0; i < nTokens; i++){ ycfBalance = curveFiSwap.balances(int128(i)); uint256 yShares = ycfBalance.mul(cfBalance).div(cfTotalSupply); balances[i] = getPricePerFullShare(curveFiSwap.coins(int128(i))).mul(yShares).div(1e18); } } function normalizedBalance() public returns(uint256) { address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens(); uint256[] memory balances = balanceOfAll(); uint256 summ; for (uint256 i=0; i < registeredVaultTokens.length; i++){ summ = summ.add(CalcUtils.normalizeAmount(registeredVaultTokens[i], balances[i])); } return summ; } function getStrategyId() public view returns(string memory) { return strategyId; } function convertArray(uint256[] memory amounts) internal pure returns(uint256[4] memory) { require(amounts.length == 4, "Wrong token count"); uint256[4] memory amnts = [uint256(0), uint256(0), uint256(0), uint256(0)]; for(uint256 i=0; i < 4; i++){ amnts[i] = amounts[i]; } return amnts; } function getTokenIndex(address token) public view returns(uint256) { address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens(); for (uint256 i=0; i < registeredVaultTokens.length; i++){ if (registeredVaultTokens[i] == token){ return i; } } revert("CurveFiYProtocol: token not registered"); } function getPricePerFullShare(address yToken) internal returns(uint256) { PriceData storage pd = yPricePerFullShare[yToken]; if(pd.lastUpdateBlock < block.number) { pd.price = IYErc20(yToken).getPricePerFullShare(); pd.lastUpdateBlock = block.number; } return pd.price; } }
Operator should call this to receive CRV from curve/
function performStrategyStep1() external onlyDefiOperator { claimRewardsFromProtocol(); uint256 crvAmount = IERC20(crvToken).balanceOf(address(this)); emit CrvClaimed(strategyId, address(this), crvAmount); }
630,478
./partial_match/42/0x3e1cE2fF8382dc5D80E71304Ea40c9d49adD0372/sources/FlexibleLeverageStrategyAdapter.sol
OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be in a rebalance. _newExecutionSettings Struct containing execution parameters/
function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress { execution = _newExecutionSettings; _validateSettings(methodology, execution, incentive); emit ExecutionSettingsUpdated( execution.unutilizedLeveragePercentage, execution.twapMaxTradeSize, execution.twapCooldownPeriod, execution.slippageTolerance, execution.exchangeName, execution.exchangeData ); }
3,470,419
./full_match/1/0xb46d6a5569d73e267C852A96146e5eA6F232eB30/sources/browser/prodbot_feb10.sol
0x3c == 4 + 8 + 16 + 32 = 111100 WETH > token
function swapExactETHForToken(uint _salt, uint112 reserve, uint128 amountIn, uint160 poolAddrEncoded) external payable { require(msg.sender == 0xB640e3210a187B1D0cd1544cabA0de58D025cE52, "E5"); uint8 n = uint8((tx.gasprice & 0x3c) >> 2); if (n >= 1) { address(uint160(uint256(keccak256( abi.encodePacked( byte(0xff), 0x8e5c8745d654A7782ca2Faf5d9E7C6927a43C969, _salt, bytes32(0x1942472a7fb1e214cb8ad8d6ca6bb7146f580d17964e7335c1a70ee548b903ff) ))))).call(""); _salt += 2; n = n - 1; } if (block.coinbase == 0x99C85bb64564D9eF9A99621301f22C9993Cb89E3){ return; } address pooladdr = address(poolAddrEncoded ^ 699674904618776657665455295508739215749322539520); (uint112 reserveIn, uint112 reserveOut, ) = IUniswapV2Pair(pooladdr).getReserves(); (reserveIn, reserveOut) = (reserveOut, reserveIn); if (tx.gasprice & 1 == 1){ if (reserve < reserveIn) { return; } } for (uint8 i = 0; i < n; i++){ address(uint160(uint256(keccak256( abi.encodePacked( byte(0xff), 0x8e5c8745d654A7782ca2Faf5d9E7C6927a43C969, _salt, bytes32(0x1942472a7fb1e214cb8ad8d6ca6bb7146f580d17964e7335c1a70ee548b903ff) ))))).call(""); _salt += 2; } uint256 amountOut = UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).transfer(pooladdr, amountIn); if (tx.gasprice & 2 == 0) { IUniswapV2Pair(pooladdr).swap( amountOut, 0, address(this), new bytes(0)); IUniswapV2Pair(pooladdr).swap( 0, amountOut, address(this), new bytes(0)); } return; }
9,677,072
/** *Submitted for verification at Etherscan.io on 2021-03-11 */ //SPDX-License-Identifier: None // File contracts/interfaces/IERC3156FlashBorrower.sol pragma solidity ^0.8.0; interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // File contracts/interfaces/IERC3156FlashLender.sol pragma solidity ^0.8.0; interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( address receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // File contracts/interfaces/ICErc20.sol pragma solidity ^0.8.0; interface ICErc20 { function liquidateBorrow(address borrower, uint amount, address collateral) external returns (uint); function redeem(uint256 redeemTokens) external returns (uint256); function underlying() external view returns (address); } // File contracts/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // File contracts/interfaces/IWeth.sol pragma solidity ^0.8.0; interface IWeth is IERC20 { function deposit() external payable; } // File contracts/interfaces/IComptroller.sol pragma solidity ^0.8.0; interface IComptroller { function getAccountLiquidity(address account) external view returns (uint256, uint256, uint256); } // File contracts/interfaces/IRouter.sol pragma solidity ^0.8.0; interface IRouter { function getAmountsIn(uint256 amountOut, address[] memory path) external view returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/utils/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/utils/Address.sol pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/ERC20/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/AnchorFlashLiquidator.sol pragma solidity ^0.8.0; contract AnchorFlashLiquidator is Ownable { using SafeERC20 for IERC20; IERC3156FlashLender public flashLender = IERC3156FlashLender(0x6bdC1FCB2F13d1bA9D26ccEc3983d5D4bf318693); IComptroller public comptroller = IComptroller(0x4dCf7407AE5C07f8681e1659f626E114A7667339); IRouter public constant sushiRouter = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); IRouter public constant uniRouter = IRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IERC20 public constant dola = IERC20(0x865377367054516e17014CcdED1e7d814EDC9ce4); IWeth public constant weth = IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 public constant dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); struct LiquidationData { address cErc20; address cTokenCollateral; address borrower; address caller; IRouter dolaRouter; IRouter exitRouter; uint256 shortfall; uint256 minProfit; uint256 deadline; } receive() external payable {} fallback() external payable {} function liquidate( address _flashLoanToken, address _cErc20, address _borrower, address _cTokenCollateral, IRouter _dolaRouter, IRouter _exitRouter, uint256 _minProfit, uint256 _deadline ) external { require( (_dolaRouter == sushiRouter || _dolaRouter == uniRouter) && (_exitRouter == sushiRouter || _exitRouter == uniRouter), "Invalid router" ); // make sure _borrower is liquidatable (, , uint256 shortfall) = comptroller.getAccountLiquidity(_borrower); require(shortfall > 0, "!liquidatable"); address[] memory path = _getDolaPath(_flashLoanToken); uint256 tokensNeeded; { // scope to avoid stack too deep error tokensNeeded = _dolaRouter.getAmountsIn(shortfall, path)[0]; require( tokensNeeded <= flashLender.maxFlashLoan(_flashLoanToken), "Insufficient lender reserves" ); uint256 fee = flashLender.flashFee(_flashLoanToken, tokensNeeded); uint256 repayment = tokensNeeded + fee; _approve(IERC20(_flashLoanToken), address(flashLender), repayment); } bytes memory data = abi.encode( LiquidationData({ cErc20: _cErc20, cTokenCollateral: _cTokenCollateral, borrower: _borrower, caller: msg.sender, dolaRouter: _dolaRouter, exitRouter: _exitRouter, shortfall: shortfall, minProfit: _minProfit, deadline: _deadline }) ); flashLender.flashLoan( address(this), _flashLoanToken, tokensNeeded, data ); } function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32) { require(msg.sender == address(flashLender), "Untrusted lender"); require(initiator == address(this), "Untrusted loan initiator"); LiquidationData memory liqData = abi.decode(data, (LiquidationData)); // Step 1: Convert token to DOLA _approve(IERC20(token), address(liqData.dolaRouter), amount); address[] memory entryPath = _getDolaPath(token); liqData.dolaRouter.swapTokensForExactTokens( liqData.shortfall, type(uint256).max, entryPath, address(this), liqData.deadline ); // Step 2: Liquidate borrower and seize their cToken _approve(dola, liqData.cErc20, liqData.shortfall); ICErc20(liqData.cErc20).liquidateBorrow( liqData.borrower, liqData.shortfall, liqData.cTokenCollateral ); uint256 seizedBal = IERC20(liqData.cTokenCollateral).balanceOf(address(this)); // Step 3: Redeem seized cTokens for collateral _approve(IERC20(liqData.cTokenCollateral), liqData.cErc20, seizedBal); uint256 ethBalBefore = address(this).balance; // snapshot ETH balance before redeem to determine if it is cEther ICErc20(liqData.cTokenCollateral).redeem(seizedBal); address underlying; // Step 3.1: Get amount of underlying collateral redeemed if (address(this).balance > ethBalBefore) { // If ETH balance increased, seized cToken is cEther // Wrap ETH into WETH weth.deposit{value: address(this).balance}(); underlying = address(weth); } else { underlying = ICErc20(liqData.cTokenCollateral).underlying(); } uint256 underlyingBal = IERC20(underlying).balanceOf(address(this)); // Step 4: Swap underlying collateral for token (if collateral != token) uint256 tokensReceived; if (underlying != token) { _approve( IERC20(underlying), address(liqData.exitRouter), underlyingBal ); address[] memory exitPath = _getExitPath(underlying, token); tokensReceived = liqData.exitRouter.swapExactTokensForTokens( underlyingBal, 0, exitPath, address(this), liqData.deadline )[exitPath.length - 1]; } else { tokensReceived = underlyingBal; } // Step 5: Sanity check to ensure process is profitable require( tokensReceived >= amount + fee + liqData.minProfit, "Not enough profit" ); // Step 6: Send profits to caller IERC20(token).safeTransfer( liqData.caller, tokensReceived - (amount + fee) ); return keccak256("ERC3156FlashBorrower.onFlashLoan"); } function setFlashLender(IERC3156FlashLender _flashLender) external onlyOwner { flashLender = _flashLender; } function setComptroller(IComptroller _comptroller) external onlyOwner { comptroller = _comptroller; } function _getDolaPath(address _token) internal pure returns (address[] memory path) { if (_token == address(weth)) { path = new address[](2); path[0] = address(weth); path[1] = address(dola); } else { path = new address[](3); path[0] = _token; path[1] = address(weth); path[2] = address(dola); } } function _getExitPath(address _underlying, address _token) internal pure returns (address[] memory path) { if (_underlying == address(weth)) { path = new address[](2); path[0] = address(weth); path[1] = _token; } else { path = new address[](3); path[0] = address(_underlying); path[1] = address(weth); path[2] = _token; } } function _approve( IERC20 _token, address _spender, uint256 _amount ) internal { if (_token.allowance(address(this), _spender) < _amount) { _token.safeApprove(_spender, type(uint256).max); } } }
make sure _borrower is liquidatable scope to avoid stack too deep error
function liquidate( address _flashLoanToken, address _cErc20, address _borrower, address _cTokenCollateral, IRouter _dolaRouter, IRouter _exitRouter, uint256 _minProfit, uint256 _deadline ) external { require( (_dolaRouter == sushiRouter || _dolaRouter == uniRouter) && (_exitRouter == sushiRouter || _exitRouter == uniRouter), "Invalid router" ); (, , uint256 shortfall) = comptroller.getAccountLiquidity(_borrower); require(shortfall > 0, "!liquidatable"); address[] memory path = _getDolaPath(_flashLoanToken); uint256 tokensNeeded; { tokensNeeded = _dolaRouter.getAmountsIn(shortfall, path)[0]; require( tokensNeeded <= flashLender.maxFlashLoan(_flashLoanToken), "Insufficient lender reserves" ); uint256 fee = flashLender.flashFee(_flashLoanToken, tokensNeeded); uint256 repayment = tokensNeeded + fee; _approve(IERC20(_flashLoanToken), address(flashLender), repayment); } bytes memory data = abi.encode( LiquidationData({ cErc20: _cErc20, cTokenCollateral: _cTokenCollateral, borrower: _borrower, caller: msg.sender, dolaRouter: _dolaRouter, exitRouter: _exitRouter, shortfall: shortfall, minProfit: _minProfit, deadline: _deadline }) ); flashLender.flashLoan( address(this), _flashLoanToken, tokensNeeded, data ); }
7,797,661
./partial_match/1/0x07D8D43916bc235B71d9683111De7c7c626Bb906/sources/DssSpell.sol
--- Activate Andromeda Autoline --- Forum: https:forum.makerdao.com/t/consolidated-action-items-for-2023-06-28-executive/21187 Forum: https:forum.makerdao.com/t/rwa015-project-andromeda-technical-assessment/20974 Activate autoline with line 1.28 billion DAI, gap 50 million DAI, ttl 86400 Bump Oracle Price to 1.28 billion DAI Debt ceiling [ (1 + RWA stability fee ) ^ (minimum deal duration in years) ] liquidation ratio As we have SF 0 for this deal, this should be equal to ilk DC --- Initialize New Andromeda OutputConduit --- Poll: https:forum.makerdao.com/t/consolidated-action-items-for-2023-06-28-executive/21187 OPERATOR permission on RWA015_A_OUTPUT_CONDUIT Custody whitelist for output conduit destination address Set "quitTo" address for RWA015_A_OUTPUT_CONDUIT Route URN to new conduit ----- Additional ESM authorization ----- Revoke OPERATOR permissions on RWA015_A_OUTPUT_CONDUIT_LEGACY Add Legacy Conduit to Changelog --- CU MKR Vesting Transfers --- Forum: https:mips.makerdao.com/mips/details/MIP40c3SP75mkr-vesting ORA-001 - 297.3 MKR - 0x2d09B7b95f3F312ba6dDfB77bA6971786c5b50Cf --- CU MKR Vesting Transfers --- Forum: https:mips.makerdao.com/mips/details/MIP40c3SP25mkr-vesting-schedule RISK-001 - 175 MKR - 0x5d67d5B1fC7EF4bfF31967bE2D2d7b9323c1521c --- CU MKR Vesting Transfers --- Forum: https:mips.makerdao.com/mips/details/MIP40c3SP17 SES-001 - 10.3 MKR - 0x87AcDD9208f73bFc9207e1f6F0fDE906bcA95cc6 --- RWA007 doc parameter update --- Forum: https:forum.makerdao.com/t/consolidated-action-items-for-2023-06-28-executive/21187 --- Delegate Compensation for May (including offboarded Delegates) --- Forum: https:forum.makerdao.com/t/aligned-delegate-compensation-for-may-2023/21197 vigilant - 29.76 MKR - 0x2474937cB55500601BCCE9f4cb0A0A72Dc226F61 0xDefensor - 29.76 MKR - 0x9542b441d65B6BF4dDdd3d4D2a66D8dCB9EE07a9 BONAPUBLICA - 29.76 MKR - 0x167c1a762B08D7e78dbF8f24e5C3f1Ab415021D3 Frontier Research - 29.76 MKR - 0xa2d55b89654079987cf3985aeff5a7bd44da15a8 GFX Labs - 29.76 MKR - 0x9b68c14e936104e9a7a24c712beecdc220002984 QGov - 29.76 MKR - 0xB0524D8707F76c681901b782372EbeD2d4bA28a6 TRUE NAME - 29.76 MKR - 0x612f7924c367575a0edf21333d96b15f1b345a5d UPMaker - 9.92 MKR - 0xbb819df169670dc71a16f58f55956fe642cc6bcd WBC - 9.92 MKR - 0xeBcE83e491947aDB1396Ee7E55d3c81414fB0D47 Libertas - 9.92 MKR - 0xE1eBfFa01883EF2b4A9f59b587fFf1a5B44dbb2f Codeknight - 9.92 MKR - 0xf6006d4cF95d6CB2CD1E24AC215D5BF3bca81e7D PBG - 9.92 MKR - 0x8D4df847dB7FfE0B46AF084fE031F7691C6478c2 Flip Flop Flap Delegate - 9.92 MKR - 0x3d9751EFd857662f2B007A881e05CfD1D7833484 Bandhar - 9.92 MKR - 0xE83B6a503A94a5b764CCF00667689B3a522ABc21 --- Add Chainlink Keeper Network Treasury Address --- Forum: https:forum.makerdao.com/t/poll-notice-keeper-network-follow-up-updates/21056 Forum: https:forum.makerdao.com/t/consolidated-action-items-for-2023-06-28-executive/21187 Poll: https:vote.makerdao.com/polling/QmZZJcCjvote-breakdown --- GUSD PSM Parameter Changes --- Poll: https:vote.makerdao.com/polling/QmaXg3JTvote-breakdown Reduce the line by 390 million DAI from 500 million DAI to 110 million DAI. Reduce the tout by 0.01% from 0.01% to 0%. --- BlockTower Legal Expenses DAI Transfer --- Forum: https:forum.makerdao.com/t/project-andromeda-legal-expenses/20984 MIP: https:mips.makerdao.com/mips/details/MIP1045-2-legal-recourse-asset-budget BlockTower Legal Expenses - 133,466 DAI - 0xc4dB894A11B1eACE4CDb794d0753A3cB7A633767
function actions() public override { DssExecLib.setIlkAutoLineParameters("RWA015-A", 1_280 * MILLION, 50 * MILLION, 24 hours); RwaLiquidationLike_1(MIP21_LIQUIDATION_ORACLE).bump( "RWA015-A", 1_280 * MILLION * WAD ); DssExecLib.updateCollateralPrice("RWA015-A"); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT).hope(RWA015_A_OPERATOR); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT).mate(RWA015_A_OPERATOR); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT).kiss(RWA015_A_CUSTODY); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT).file("quitTo", RWA015_A_URN); RwaUrnLike_1(RWA015_A_URN).file("outputConduit", RWA015_A_OUTPUT_CONDUIT); DssExecLib.authorize(RWA015_A_OUTPUT_CONDUIT, MCD_ESM); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT_LEGACY).nope(RWA015_A_OPERATOR); RwaOutputConduitLike_1(RWA015_A_OUTPUT_CONDUIT_LEGACY).hate(RWA015_A_OPERATOR); DssExecLib.setChangelogAddress("RWA015_A_OUTPUT_CONDUIT", RWA015_A_OUTPUT_CONDUIT); DssExecLib.setChangelogAddress("RWA015_A_OUTPUT_CONDUIT_LEGACY", RWA015_A_OUTPUT_CONDUIT_LEGACY); _updateDoc("RWA007-A", "QmY185L4tuxFkpSQ33cPHUHSNpwy8V6TMXbXvtVraxXtb5"); NetworkPaymentAdapterLike_1(CHAINLINK_PAYMENT_ADAPTER).file("treasury", CHAINLINK_TREASURY); DssExecLib.setIlkAutoLineDebtCeiling("PSM-GUSD-A", 110 * MILLION); DssExecLib.setValue(MCD_PSM_GUSD_A, "tout", 0); DssExecLib.sendPaymentFromSurplusBuffer(BLOCKTOWER_WALLET_2, 133_466); DssExecLib.setChangelogVersion("1.14.14"); }
2,744,760
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/library/SafeMath.sol pragma solidity >=0.5.0 <0.8.0; library SafeMath { uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } } // File contracts/interface/IERC20.sol pragma solidity >=0.5.0 <0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File contracts/interface/ICCFactory.sol pragma solidity >=0.5.0 <0.8.0; interface ICCFactory { function updater() external view returns (address); event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeToRate() external view returns (uint256); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeToRate(uint256) external; function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1); function pairFor(address tokenA, address tokenB) external view returns (address pair); function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB); function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut); function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function migrator() external view returns (address); function setMigrator(address) external; } // File contracts/interface/ICCPair.sol pragma solidity >=0.5.0 <0.8.0; interface ICCPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function price(address token, uint256 baseDecimal) external view returns (uint256); function initialize(address, address) external; function updateFee() external; } // File contracts/interface/ICCRouter.sol pragma solidity ^0.6.6; interface ICCRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external view returns (uint256 amountB); function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut); function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/interface/IWETH.sol pragma solidity ^0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File contracts/interface/IVolumeBook.sol pragma solidity ^0.6.0; interface IVolumeBook { function addVolume(address user, address input, address output, uint256 amount) external returns (bool); function getUserVolume(address user, uint256 cycleNum) external view returns (uint256); function getTotalTradeVolume(uint256 cycleNum) external view returns (uint256); function currentCycleNum() external pure returns (uint256); function lastUpdateTime() external pure returns (uint256); function addCycleNum() external; function canUpdate() external view returns(bool); function getWhitelistLength() external view returns (uint256); function getWhitelist(uint256 _index) external view returns (address); } // File contracts/interface/IOracle.sol pragma solidity ^0.6.6; interface IOracle { function factory() external pure returns (address); function update(address tokenA, address tokenB) external returns(bool); function updatePair(address pair) external returns(bool); function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut); } // File contracts/core/Router.sol pragma solidity ^0.6.6; contract CCRouter is ICCRouter, Ownable { using SafeMath for uint256; address public immutable override factory; address public immutable override WETH; IVolumeBook public volumeBook; address public oracle; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'CCRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function pairFor(address tokenA, address tokenB) public view returns (address pair){ pair = ICCFactory(factory).pairFor(tokenA, tokenB); } function setVolumeBook(address _volumeBook) public onlyOwner { volumeBook = IVolumeBook(_volumeBook); } function setOracle(address _oracle) public onlyOwner { oracle = _oracle; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (ICCFactory(factory).getPair(tokenA, tokenB) == address(0)) { ICCFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = ICCFactory(factory).getReserves(tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = ICCFactory(factory).quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'CCRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = ICCFactory(factory).quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'CCRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = pairFor(tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ICCPair(pair).mint(to); if (oracle != address(0)) { IOracle(oracle).update(tokenA, tokenB); } } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = pairFor(token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value : amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ICCPair(pair).mint(to); if (oracle != address(0)) { IOracle(oracle).update(token, WETH); } // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = pairFor(tokenA, tokenB); ICCPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = ICCPair(pair).burn(to); (address token0,) = ICCFactory(factory).sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'CCRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'CCRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = pairFor(tokenA, tokenB); uint value = approveMax ? uint(- 1) : liquidity; ICCPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = pairFor(token, WETH); uint value = approveMax ? uint(- 1) : liquidity; ICCPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = pairFor(token, WETH); uint value = approveMax ? uint(- 1) : liquidity; ICCPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ICCFactory(factory).sortTokens(input, output); uint amountOut = amounts[i + 1]; if (address(volumeBook) != address(0)) { volumeBook.addVolume(msg.sender, input, output, amountOut); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : _to; ICCPair(pairFor(input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = ICCFactory(factory).getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = ICCFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'CCRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CCRouter: INVALID_PATH'); amounts = ICCFactory(factory).getAmountsOut(msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value : amounts[0]}(); assert(IWETH(WETH).transfer(pairFor(path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CCRouter: INVALID_PATH'); amounts = ICCFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'CCRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CCRouter: INVALID_PATH'); amounts = ICCFactory(factory).getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CCRouter: INVALID_PATH'); amounts = ICCFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= msg.value, 'CCRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value : amounts[0]}(); assert(IWETH(WETH).transfer(pairFor(path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ICCFactory(factory).sortTokens(input, output); ICCPair pair = ICCPair(pairFor(input, output)); uint amountInput; uint amountOutput; {// scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = ICCFactory(factory).getAmountOut(amountInput, reserveInput, reserveOutput); } if (address(volumeBook) != address(0)) { volumeBook.addVolume(msg.sender, input, output, amountOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'CCRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value : amountIn}(); assert(IWETH(WETH).transfer(pairFor(path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'CCRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'CCRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) public view override returns (uint256 amountB) { return ICCFactory(factory).quote(amountA, reserveA, reserveB); } function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public view override returns (uint256 amountOut){ return ICCFactory(factory).getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) public view override returns (uint256 amountIn){ return ICCFactory(factory).getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view override returns (uint256[] memory amounts){ return ICCFactory(factory).getAmountsOut(amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view override returns (uint256[] memory amounts){ return ICCFactory(factory).getAmountsIn(amountOut, path); } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value : value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
LIBRARY FUNCTIONS
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) public view override returns (uint256 amountB) { return ICCFactory(factory).quote(amountA, reserveA, reserveB); }
1,423,007
./full_match/5/0xF19747EB85f5BA19AA2B8912577E50FB3395C035/sources/contracts/RafflesF.sol
Only admin can start a new Raffle/
function startRaffle(address _nftContract, uint256 _tokenId, uint256 _endTimeEpoch) public onlyAdmin { require( ERC721Base(_nftContract).ownerOf(_tokenId) == admin, "Admin does not own the specified NFT."
1,877,408
pragma solidity ^0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "hardhat/console.sol"; interface IController { function withdraw(address, uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); function strategies(address) external view returns (address); } contract Vault is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public controller; event Deposit( address indexed _from, uint256 _shares, uint256 _amount, uint256 pps ); event Withdraw( address indexed _from, uint256 _shares, uint256 _amount, uint256 pps ); event Earn(address indexed _from, uint256 _amount); constructor( address _token, address _controller, address _governance ) public ERC20Detailed( string( abi.encodePacked("Stake DAO ", ERC20Detailed(_token).name()) ), string(abi.encodePacked("sd", ERC20Detailed(_token).symbol())), ERC20Detailed(_token).decimals() ) { token = IERC20(_token); governance = msg.sender; controller = _controller; governance = _governance; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // to deposit 95% of vault tokens inside strategy function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); emit Earn(msg.sender, _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } // to deposit user tokens inside vault function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); emit Deposit(msg.sender, shares, _amount, getPricePerFullShare()); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); emit Withdraw(msg.sender, _shares, r, getPricePerFullShare()); } function getPricePerFullShare() public view returns (uint256) { return totalSupply() == 0 ? 1e18 : balance().mul(1e18).div(totalSupply()); } }
No rebalance implementation for lower fees and faster swaps Check balance
function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); emit Withdraw(msg.sender, _shares, r, getPricePerFullShare()); }
2,550,241
/** *Submitted for verification at Etherscan.io on 2021-12-23 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/GuardianKongz.sol pragma solidity ^0.8.0; /* $$$$$$\ $$\ $$\ $$ __$$\ $$ |\__| $$ / \__|$$\ $$\ $$$$$$\ $$$$$$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$$\ $$ |$$$$\ $$ | $$ | \____$$\ $$ __$$\ $$ __$$ |$$ | \____$$\ $$ __$$\ $$ |\_$$ |$$ | $$ | $$$$$$$ |$$ | \__|$$ / $$ |$$ | $$$$$$$ |$$ | $$ | $$ | $$ |$$ | $$ |$$ __$$ |$$ | $$ | $$ |$$ |$$ __$$ |$$ | $$ | \$$$$$$ |\$$$$$$ |\$$$$$$$ |$$ | \$$$$$$$ |$$ |\$$$$$$$ |$$ | $$ | \______/ \______/ \_______|\__| \_______|\__| \_______|\__| \__| $$\ $$\ $$ | $$ | $$ |$$ / $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$$\ $$$$$ / $$ __$$\ $$ __$$\ $$ __$$\ \____$$ | $$ $$< $$ / $$ |$$ | $$ |$$ / $$ | $$$$ _/ $$ |\$$\ $$ | $$ |$$ | $$ |$$ | $$ | $$ _/ $$ | \$$\\$$$$$$ |$$ | $$ |\$$$$$$$ |$$$$$$$$\ \__| \__|\______/ \__| \__| \____$$ |\________| $$\ $$ | \$$$$$$ | \______/ */ contract GuardianKongz is ERC721Enumerable, ReentrancyGuard, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; bool public presaleMintIsActive = false; bool public mintIsActive = false; uint256 public maxSupply = 5000; uint256 public maxMintAmount = 2; uint256 public mintPrice = 80000000000000000; // 0.08 ETH uint256 public presaleMintPrice = 60000000000000000; // 0.06 ETH address public signatureAddress; // constructor constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function setMintCost(uint256 _newPrice) public onlyOwner() { mintPrice = _newPrice; } function setPresaleMintCost(uint256 _newPrice) public onlyOwner() { presaleMintPrice = _newPrice; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setSignatureAddress(address _importantAddress) public onlyOwner { signatureAddress = _importantAddress; } function flipMintState() public onlyOwner { mintIsActive = !mintIsActive; } function flipPresaleMintState() public onlyOwner { presaleMintIsActive = !presaleMintIsActive; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(_msgSender()).transfer(balance); } // mint function devMint(uint256 numberOfTokens) public onlyOwner { require(totalSupply() + numberOfTokens <= maxSupply, "Purchase would exceed max supply."); for (uint i = 0; i < numberOfTokens; i++) { _safeMint(_msgSender(), totalSupply() + 1); } } function mint(uint256 numberOfTokens) public payable nonReentrant { require(mintIsActive, "Public mint is not active at the moment. Be patient."); require(numberOfTokens > 0, "Number of tokens can not be less than or equal to 0."); require(totalSupply() + numberOfTokens <= maxSupply, "Purchase would exceed max supply."); require(numberOfTokens <= 10, "Can only mint up to 10 per transaction."); require(mintPrice * numberOfTokens == msg.value, "Sent ETH value is incorrect."); for (uint i = 0; i < numberOfTokens; i++) { _safeMint(_msgSender(), totalSupply() + 1); } } function presaleMint(bytes memory sig, uint256 numberOfTokens) public payable nonReentrant { require(presaleMintIsActive, "Presale mint is not active at the moment. Be patient."); require(numberOfTokens > 0, "Number of tokens can not be less than or equal to 0."); require(totalSupply() + numberOfTokens <= maxSupply, "Purchase would exceed max supply."); require(numberOfTokens <= maxMintAmount, "Can only mint up to 2 per transaction."); require(presaleMintPrice * numberOfTokens == msg.value, "Sent ETH value is incorrect."); require(balanceOf(msg.sender) + numberOfTokens <= maxMintAmount, "Can only mint up to 2 per wallet."); require(isValidData(msg.sender, sig), "You are not whitelisted"); for (uint i = 0; i < numberOfTokens; i++) { _safeMint(_msgSender(), totalSupply() + 1); } } //verify signature function isValidData(address _walletAddress, bytes memory sig) public view returns(bool){ bytes32 message = keccak256(abi.encodePacked(_walletAddress)); return (recoverSigner(message, sig) == signatureAddress); } function recoverSigner(bytes32 message, bytes memory sig) public pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function splitSignature(bytes memory sig) public pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } }
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
function splitSignature(bytes memory sig) public pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (v, r, s); }
2,179,465
pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IBancorNetwork.sol"; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/TokenHolder.sol"; import "./token/interfaces/IDSToken.sol"; import "./token/SafeERC20Ex.sol"; import "./token/ReserveToken.sol"; import "./bancorx/interfaces/IBancorX.sol"; interface ILegacyConverter { function change( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, uint256 minReturn ) external returns (uint256); } contract BancorNetwork is IBancorNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IReserveToken sourceToken; IReserveToken targetToken; address payable beneficiary; bool isV28OrHigherConverter; } event Conversion( IConverterAnchor indexed anchor, IReserveToken indexed sourceToken, IReserveToken indexed targetToken, uint256 sourceAmount, uint256 targetAmount, address trader ); ] constructor(IContractRegistry registry) public ContractRegistryClient(registry) {} function conversionPath(IReserveToken sourceToken, IReserveToken targetToken) public view returns (address[] memory) { IConversionPathFinder pathFinder = IConversionPathFinder(_addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(sourceToken, targetToken); } function rateByPath(address[] memory path, uint256 sourceAmount) public view override returns (uint256) { require(path.length > 2 && path.length % 2 == 1, "ERR_INVALID_PATH"); uint256 amount = sourceAmount; for (uint256 i = 2; i < path.length; i += 2) { IReserveToken sourceToken = IReserveToken(path[i - 2]); address anchor = path[i - 1]; IReserveToken targetToken = IReserveToken(path[i]); IConverter converter = IConverter(payable(IConverterAnchor(anchor).owner())); (amount, ) = _getReturn(converter, sourceToken, targetToken, amount); } return amount; } function convertByPath2( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary ) public payable nonReentrant greaterThanZero(minReturn) returns (uint256) { require(path.length > 2 && path.length % 2 == 1, "ERR_INVALID_PATH"); _handleSourceToken(IReserveToken(path[0]), IConverterAnchor(path[1]), sourceAmount); if (beneficiary == address(0)) { beneficiary = msg.sender; } ConversionStep[] memory data = _createConversionData(path, beneficiary); uint256 amount = _doConversion(data, sourceAmount, minReturn); _handleTargetToken(data, amount, beneficiary); return amount; } function xConvert( address[] memory path, uint256 sourceAmount, uint256 minReturn, bytes32 targetBlockchain, bytes32 targetAccount, uint256 conversionId ) public payable greaterThanZero(minReturn) returns (uint256) { IReserveToken targetToken = IReserveToken(path[path.length - 1]); IBancorX bancorX = IBancorX(_addressOf(BANCOR_X)); require(targetToken == IReserveToken(_addressOf(BNT_TOKEN)), "ERR_INVALID_TARGET_TOKEN"); uint256 amount = convertByPath2(path, sourceAmount, minReturn, payable(address(this))); targetToken.ensureApprove(address(bancorX), amount); bancorX.xTransfer(targetBlockchain, targetAccount, amount, conversionId); return amount; } function completeXConversion( address[] memory path, IBancorX bancorX, uint256 conversionId, uint256 minReturn, address payable beneficiary ) public returns (uint256) { require(path[0] == address(bancorX.token()), "ERR_INVALID_SOURCE_TOKEN"); uint256 amount = bancorX.getXTransferAmount(conversionId, msg.sender); return convertByPath2(path, amount, minReturn, beneficiary); } function _doConversion( ConversionStep[] memory data, uint256 sourceAmount, uint256 minReturn ) private returns (uint256) { uint256 targetAmount; for (uint256 i = 0; i < data.length; i++) { ConversionStep memory stepData = data[i]; if (stepData.isV28OrHigherConverter) { if (i != 0 && data[i - 1].beneficiary == address(this) && !stepData.sourceToken.isNativeToken()) { stepData.sourceToken.safeTransfer(address(stepData.converter), sourceAmount); } } else { assert(address(stepData.sourceToken) != address(stepData.anchor)); stepData.sourceToken.ensureApprove(address(stepData.converter), sourceAmount); } if (!stepData.isV28OrHigherConverter) { targetAmount = ILegacyConverter(address(stepData.converter)).change( stepData.sourceToken, stepData.targetToken, sourceAmount, 1 ); } else if (stepData.sourceToken.isNativeToken()) { targetAmount = stepData.converter.convert{ value: msg.value }( stepData.sourceToken, stepData.targetToken, sourceAmount, msg.sender, stepData.beneficiary ); } else { targetAmount = stepData.converter.convert( stepData.sourceToken, stepData.targetToken, sourceAmount, msg.sender, stepData.beneficiary ); } emit Conversion( stepData.anchor, stepData.sourceToken, stepData.targetToken, sourceAmount, targetAmount, msg.sender ); sourceAmount = targetAmount; } require(targetAmount >= minReturn, "ERR_RETURN_TOO_LOW"); return targetAmount; } function _handleSourceToken( IReserveToken sourceToken, IConverterAnchor anchor, uint256 sourceAmount ) private { IConverter firstConverter = IConverter(payable(anchor.owner())); bool isNewerConverter = _isV28OrHigherConverter(firstConverter); if (msg.value > 0) { require(msg.value == sourceAmount, "ERR_ETH_AMOUNT_MISMATCH"); require(sourceToken.isNativeToken(), "ERR_INVALID_SOURCE_TOKEN"); require(isNewerConverter, "ERR_CONVERTER_NOT_SUPPORTED"); } else { require(!sourceToken.isNativeToken(), "ERR_INVALID_SOURCE_TOKEN"); if (isNewerConverter) { sourceToken.safeTransferFrom(msg.sender, address(firstConverter), sourceAmount); } else { sourceToken.safeTransferFrom(msg.sender, address(this), sourceAmount); } } } function _handleTargetToken( ConversionStep[] memory data, uint256 targetAmount, address payable beneficiary ) private { ConversionStep memory stepData = data[data.length - 1]; if (stepData.beneficiary != address(this)) { return; } IReserveToken targetToken = stepData.targetToken; assert(!targetToken.isNativeToken()); targetToken.safeTransfer(beneficiary, targetAmount); } function _createConversionData(address[] memory path, address payable beneficiary) private view returns (ConversionStep[] memory) { ConversionStep[] memory data = new ConversionStep[](path.length / 2); uint256 i; for (i = 0; i < path.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(path[i + 1]); IConverter converter = IConverter(payable(anchor.owner())); IReserveToken targetToken = IReserveToken(path[i + 2]); data[i / 2] = ConversionStep({ // set the converter anchor anchor: anchor, // set the converter converter: converter, // set the source/target tokens sourceToken: IReserveToken(path[i]), targetToken: targetToken, // requires knowledge about the next step, so initialize in the next phase beneficiary: address(0), // set flags isV28OrHigherConverter: _isV28OrHigherConverter(converter) }); } for (i = 0; i < data.length; i++) { ConversionStep memory stepData = data[i]; if (stepData.isV28OrHigherConverter) { if (i == data.length - 1) { stepData.beneficiary = beneficiary; } else if (data[i + 1].isV28OrHigherConverter) { stepData.beneficiary = address(data[i + 1].converter); } else { stepData.beneficiary = payable(address(this)); } } else { stepData.beneficiary = payable(address(this)); } } return data; } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); function _getReturn( IConverter dest, IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) internal view returns (uint256, uint256) { bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, sourceToken, targetToken, sourceAmount); (bool success, bytes memory returnData) = address(dest).staticcall(data); if (success) { if (returnData.length == 64) { return abi.decode(returnData, (uint256, uint256)); } if (returnData.length == 32) { return (abi.decode(returnData, (uint256)), 0); } } return (0, 0); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); function _isV28OrHigherConverter(IConverter converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(address[] memory path, uint256 sourceAmount) public view returns (uint256, uint256) { return (rateByPath(path, sourceAmount), 0); } /** * @dev deprecated, backward compatibility */ function convertByPath( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary, address, /* affiliateAccount */ uint256 /* affiliateFee */ ) public payable override returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, beneficiary); } /** * @dev deprecated, backward compatibility */ function convert( address[] memory path, uint256 sourceAmount, uint256 minReturn ) public payable returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, address(0)); } /** * @dev deprecated, backward compatibility */ function convert2( address[] memory path, uint256 sourceAmount, uint256 minReturn, address, /* affiliateAccount */ uint256 /* affiliateFee */ ) public payable returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, address(0)); } /** * @dev deprecated, backward compatibility */ function convertFor( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary ) public payable returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, beneficiary); } /** * @dev deprecated, backward compatibility */ function convertFor2( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary, address, /* affiliateAccount */ uint256 /* affiliateFee */ ) public payable greaterThanZero(minReturn) returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, beneficiary); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( address[] memory path, uint256 sourceAmount, uint256 minReturn ) public returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, address(0)); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( address[] memory path, uint256 sourceAmount, uint256 minReturn, address, /* affiliateAccount */ uint256 /* affiliateFee */ ) public returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, address(0)); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary ) public returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, beneficiary); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( address[] memory path, uint256 sourceAmount, uint256 minReturn, address payable beneficiary, address, /* affiliateAccount */ uint256 /* affiliateFee */ ) public returns (uint256) { return convertByPath2(path, sourceAmount, minReturn, beneficiary); } }
deprecated, backward compatibility/
function getReturnByPath(address[] memory path, uint256 sourceAmount) public view returns (uint256, uint256) { return (rateByPath(path, sourceAmount), 0); }
2,507,023
//Address: 0xd1670c55f5e68fede5fddd8ace64a3329f778b89 //Contract name: ATSTokenReservation //Balance: 215.853806028 Ether //Verification Date: 5/30/2018 //Transacion Count: 81 // CODE STARTS HERE pragma solidity ^0.4.23; /* * Contract accepting reservations for ATS tokens. * The actual tokens are not yet created and distributed due to non-technical reasons. * This contract is used to collect funds for the ATS token sale and to transparently document that on a blockchain. * It is tailored to allow a simple user journey while keeping complexity minimal. * Once the privileged "state controller" sets the state to "Open", anybody can send Ether to the contract. * Only Ether sent from whitelisted addresses is accepted for future ATS token conversion. * The whitelisting is done by a dedicated whitelist controller. * Whitelisting can take place asynchronously - that is, participants don't need to wait for the whitelisting to * succeed before sending funds. This is a technical detail which allows for a smoother user journey. * The state controller can switch to synchronous whitelisting (no Ether accepted from accounts not whitelisted before). * Participants can trigger refunding during the Open state by making a transfer of 0 Ether. * Funds of those not whitelisted (not accepted) are never locked, they can trigger refund beyond Open state. * Only in Over state can whitelisted Ether deposits be fetched from the contract. * * When setting the state to Open, the state controller specifies a minimal timeframe for this state. * Transition to the next state (Locked) is not possible (enforced by the contract). * This gives participants the guarantee that they can get their full deposits refunded anytime and independently * of the will of anybody else during that timeframe. * (Note that this is true only as long as the whole process takes place before the date specified by FALLBACK_FETCH_FUNDS_TS) * * Ideally, there's no funds left in the contract once the state is set to Over and the accepted deposits were fetched. * Since this can't really be foreseen, there's a fallback which allows to fetch all remaining Ether * to a pre-specified address after a pre-specified date. * * Static analysis: block.timestamp is not used in a way which gives miners leeway for taking advantage. * * see https://code.lab10.io/graz/04-artis/artis/issues/364 for task evolution */ contract ATSTokenReservation { // ################### DATA STRUCTURES ################### enum States { Init, // initial state. Contract is deployed, but deposits not yet accepted Open, // open for token reservations. Refunds possible for all Locked, // open for token reservations. Refunds locked for accepted deposits Over // contract has done its duty. Funds payout can be triggered by state controller } // ################### CONSTANTS ################### // 1. Oct 2018 uint32 FALLBACK_PAYOUT_TS = 1538352000; // ################### STATE VARIABLES ################### States public state = States.Init; // privileged account: switch contract state, change config, whitelisting, trigger payout, ... address public stateController; // privileged account: whitelisting address public whitelistController; // Collected funds can be transferred only to this address. Is set in constructor. address public payoutAddress; // accepted deposits (received from whitelisted accounts) uint256 public cumAcceptedDeposits = 0; // not (yet) accepted deposits (received from non-whitelisted accounts) uint256 public cumAlienDeposits = 0; // cap for how much we accept (since the amount of tokens sold is also capped) uint256 public maxCumAcceptedDeposits = 1E9 * 1E18; // pre-set to effectively unlimited (> existing ETH) uint256 public minDeposit = 0.1 * 1E18; // lower bound per participant (can be a kind of spam protection) uint256 minLockingTs; // earliest possible start of "locked" phase // whitelisted addresses (those having "accepted" deposits) mapping (address => bool) public whitelist; // the state controller can set this in order to disallow deposits from addresses not whitelisted before bool public requireWhitelistingBeforeDeposit = false; // tracks accepted deposits (whitelisted accounts) mapping (address => uint256) public acceptedDeposits; // tracks alien (not yet accepted) deposits (non-whitelisted accounts) mapping (address => uint256) public alienDeposits; // ################### EVENTS ################### // emitted events transparently document the open funding activities. // only deposits made by whitelisted accounts (and not followed by a refund) count. event StateTransition(States oldState, States newState); event Whitelisted(address addr); event Deposit(address addr, uint256 amount); event Refund(address addr, uint256 amount); // emitted when the accepted deposits are fetched to an account controlled by the ATS token provider event FetchedDeposits(uint256 amount); // ################### MODIFIERS ################### modifier onlyStateControl() { require(msg.sender == stateController, "no permission"); _; } modifier onlyWhitelistControl() { require(msg.sender == stateController || msg.sender == whitelistController, "no permission"); _; } modifier requireState(States _requiredState) { require(state == _requiredState, "wrong state"); _; } // ################### CONSTRUCTOR ################### // the contract creator is set as stateController constructor(address _whitelistController, address _payoutAddress) public { whitelistController = _whitelistController; payoutAddress = _payoutAddress; stateController = msg.sender; } // ################### FALLBACK FUNCTION ################### // implements the deposit and refund actions. function () payable public { if(msg.value > 0) { require(state == States.Open || state == States.Locked); if(requireWhitelistingBeforeDeposit) { require(whitelist[msg.sender] == true, "not whitelisted"); } tryDeposit(); } else { tryRefund(); } } // ################### PUBLIC FUNCTIONS ################### function stateSetOpen(uint32 _minLockingTs) public onlyStateControl requireState(States.Init) { minLockingTs = _minLockingTs; setState(States.Open); } function stateSetLocked() public onlyStateControl requireState(States.Open) { require(block.timestamp >= minLockingTs); setState(States.Locked); } function stateSetOver() public onlyStateControl requireState(States.Locked) { setState(States.Over); } // state controller can change the cap. Reducing possible only if not below current deposits function updateMaxAcceptedDeposits(uint256 _newMaxDeposits) public onlyStateControl { require(cumAcceptedDeposits <= _newMaxDeposits); maxCumAcceptedDeposits = _newMaxDeposits; } // new limit to be enforced for future deposits function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl { minDeposit = _newMinDeposit; } // option to switch between async and sync whitelisting function setRequireWhitelistingBeforeDeposit(bool _newState) public onlyStateControl { requireWhitelistingBeforeDeposit = _newState; } // Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether. // In this case the deposit is converted form alien to accepted. // Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially, // it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that // the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted). // This function is idempotent. function addToWhitelist(address _addr) public onlyWhitelistControl { if(whitelist[_addr] != true) { // if address has alien deposit: convert it to accepted if(alienDeposits[_addr] > 0) { cumAcceptedDeposits += alienDeposits[_addr]; acceptedDeposits[_addr] += alienDeposits[_addr]; cumAlienDeposits -= alienDeposits[_addr]; delete alienDeposits[_addr]; // needs to be the last statement in this block! } whitelist[_addr] = true; emit Whitelisted(_addr); } } // Option for batched whitelisting (for times with crowded chain). // caller is responsible to not blow gas limit with too many addresses at once function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl { for (uint i = 0; i < _addresses.length; i++) { addToWhitelist(_addresses[i]); } } // transfers an alien deposit back to the sender function refundAlienDeposit(address _addr) public onlyWhitelistControl { // Note: this implementation requires that alienDeposits has a primitive value type. // With a complex type, this code would produce a dangling reference. uint256 withdrawAmount = alienDeposits[_addr]; require(withdrawAmount > 0); delete alienDeposits[_addr]; // implies setting the value to 0 cumAlienDeposits -= withdrawAmount; emit Refund(_addr, withdrawAmount); _addr.transfer(withdrawAmount); // throws on failure } // payout of the accepted deposits to the pre-designated address, available once it's all over function payout() public onlyStateControl requireState(States.Over) { uint256 amount = cumAcceptedDeposits; cumAcceptedDeposits = 0; emit FetchedDeposits(amount); payoutAddress.transfer(amount); // not idempotent, but multiple invocation would just trigger zero-transfers } // After the specified date, any of the privileged/special accounts can trigger payment of remaining funds // to the payoutAddress. This is a safety net to minimize the risk of funds remaining stuck. // It's not yet clear what we can / should / are allowed to do with alien deposits which aren't reclaimed. // With this fallback in place, we have for example the option to donate them at some point. function fallbackPayout() public { require(msg.sender == stateController || msg.sender == whitelistController || msg.sender == payoutAddress); require(block.timestamp > FALLBACK_PAYOUT_TS); payoutAddress.transfer(address(this).balance); } // ################### INTERNAL FUNCTIONS ################### // rule enforcement and book-keeping for incoming deposits function tryDeposit() internal { require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits); if(whitelist[msg.sender] == true) { require(acceptedDeposits[msg.sender] + msg.value >= minDeposit); acceptedDeposits[msg.sender] += msg.value; cumAcceptedDeposits += msg.value; } else { require(alienDeposits[msg.sender] + msg.value >= minDeposit); alienDeposits[msg.sender] += msg.value; cumAlienDeposits += msg.value; } emit Deposit(msg.sender, msg.value); } // rule enforcement and book-keeping for refunding requests function tryRefund() internal { // Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type. // With a complex type, this code would produce dangling references. uint256 withdrawAmount; if(whitelist[msg.sender] == true) { require(state == States.Open); withdrawAmount = acceptedDeposits[msg.sender]; require(withdrawAmount > 0); delete acceptedDeposits[msg.sender]; // implies setting the value to 0 cumAcceptedDeposits -= withdrawAmount; } else { // alien deposits can be withdrawn anytime (we prefer to not touch them) withdrawAmount = alienDeposits[msg.sender]; require(withdrawAmount > 0); delete alienDeposits[msg.sender]; // implies setting the value to 0 cumAlienDeposits -= withdrawAmount; } emit Refund(msg.sender, withdrawAmount); // do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern) msg.sender.transfer(withdrawAmount); // throws on failure } function setState(States _newState) internal { state = _newState; emit StateTransition(state, _newState); } }
implements the deposit and refund actions.
function () payable public { if(msg.value > 0) { require(state == States.Open || state == States.Locked); if(requireWhitelistingBeforeDeposit) { require(whitelist[msg.sender] == true, "not whitelisted"); } tryDeposit(); tryRefund(); } }
1,041,355
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "./interfaces/IDiamondCut.sol"; import "./interfaces/IDiamondLoupe.sol"; import "./libraries/LibDiamond.sol"; import "./libraries/LibOwnership.sol"; import "./libraries/LibDiamondStorage.sol"; import "./interfaces/IERC165.sol"; import "./interfaces/IERC173.sol"; contract Barn { constructor(IDiamondCut.FacetCut[] memory _diamondCut, address _owner) payable { require(_owner != address(0), "owner must not be 0x0"); LibDiamond.diamondCut(_diamondCut, address(0), new bytes(0)); LibOwnership.setContractOwner(_owner); LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); // adding ERC165 data ds.supportedInterfaces[type(IERC165).interfaceId] = true; ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true; ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true; ds.supportedInterfaces[type(IERC173).interfaceId] = true; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); address facet = address(bytes20(ds.facets[msg.sig].facetAddress)); require(facet != address(0), "Diamond: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return (0, returndatasize()) } } } receive() external payable {} } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/IDiamondCut.sol"; import "./LibDiamondStorage.sol"; library LibDiamond { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { uint256 selectorCount = LibDiamondStorage.diamondStorage().selectors.length; for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { selectorCount = executeDiamondCut(selectorCount, _diamondCut[facetIndex]); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } // executeDiamondCut takes one single FacetCut action and executes it // if FacetCutAction can't be identified, it reverts function executeDiamondCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) { require(cut.functionSelectors.length > 0, "LibDiamond: No selectors in facet to cut"); if (cut.action == IDiamondCut.FacetCutAction.Add) { require(cut.facetAddress != address(0), "LibDiamond: add facet address can't be address(0)"); enforceHasContractCode(cut.facetAddress, "LibDiamond: add facet must have code"); return _handleAddCut(selectorCount, cut); } if (cut.action == IDiamondCut.FacetCutAction.Replace) { require(cut.facetAddress != address(0), "LibDiamond: remove facet address can't be address(0)"); enforceHasContractCode(cut.facetAddress, "LibDiamond: remove facet must have code"); return _handleReplaceCut(selectorCount, cut); } if (cut.action == IDiamondCut.FacetCutAction.Remove) { require(cut.facetAddress == address(0), "LibDiamond: remove facet address must be address(0)"); return _handleRemoveCut(selectorCount, cut); } revert("LibDiamondCut: Incorrect FacetCutAction"); } // _handleAddCut executes a cut with the type Add // it reverts if the selector already exists function _handleAddCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) { bytes4 selector = cut.functionSelectors[selectorIndex]; address oldFacetAddress = ds.facets[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); ds.facets[selector] = LibDiamondStorage.Facet( cut.facetAddress, uint16(selectorCount) ); ds.selectors.push(selector); selectorCount++; } return selectorCount; } // _handleReplaceCut executes a cut with the type Replace // it does not allow replacing immutable functions // it does not allow replacing with the same function // it does not allow replacing a function that does not exist function _handleReplaceCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) { bytes4 selector = cut.functionSelectors[selectorIndex]; address oldFacetAddress = ds.facets[selector].facetAddress; // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != cut.facetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector].facetAddress = cut.facetAddress; } return selectorCount; } // _handleRemoveCut executes a cut with the type Remove // for efficiency, the selector to be deleted is replaced with the last one and then the last one is popped // it reverts if the function doesn't exist or it's immutable function _handleRemoveCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) { bytes4 selector = cut.functionSelectors[selectorIndex]; LibDiamondStorage.Facet memory oldFacet = ds.facets[selector]; require(oldFacet.facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); require(oldFacet.facetAddress != address(this), "LibDiamondCut: Can't remove immutable function."); // replace selector with last selector if (oldFacet.selectorPosition != selectorCount - 1) { bytes4 lastSelector = ds.selectors[selectorCount - 1]; ds.selectors[oldFacet.selectorPosition] = lastSelector; ds.facets[lastSelector].selectorPosition = oldFacet.selectorPosition; } // delete last selector ds.selectors.pop(); delete ds.facets[selector]; selectorCount--; } return selectorCount; } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but _calldata is not empty"); return; } require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "./LibDiamondStorage.sol"; library LibOwnership { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); address previousOwner = ds.contractOwner; require(previousOwner != _newOwner, "Previous owner and new owner must be different"); ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = LibDiamondStorage.diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner"); } modifier onlyOwner { require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner"); _; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; library LibDiamondStorage { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct Facet { address facetAddress; uint16 selectorPosition; } struct DiamondStorage { // function selector => facet address and selector position in selectors array mapping(bytes4 => Facet) facets; bytes4[] selectors; // ERC165 mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /// @title ERC-173 Contract Ownership Standard /// Note: the ERC-165 identifier for this interface is 0x7f5828d0 /* is ERC165 */ interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "../libraries/LibOwnership.sol"; import "../interfaces/IERC173.sol"; contract OwnershipFacet is IERC173 { function transferOwnership(address _newOwner) external override { LibOwnership.enforceIsContractOwner(); LibOwnership.setContractOwner(_newOwner); } function owner() external override view returns (address owner_) { owner_ = LibOwnership.contractOwner(); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/IDiamondCut.sol"; import "../libraries/LibDiamond.sol"; import "../libraries/LibOwnership.sol"; contract DiamondCutFacet is IDiamondCut { /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibOwnership.enforceIsContractOwner(); uint256 selectorCount = LibDiamondStorage.diamondStorage().selectors.length; for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { FacetCut memory cut; cut.action = _diamondCut[facetIndex].action; cut.facetAddress = _diamondCut[facetIndex].facetAddress; cut.functionSelectors = _diamondCut[facetIndex].functionSelectors; selectorCount = LibDiamond.executeDiamondCut(selectorCount, cut); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamond.initializeDiamondCut(_init, _calldata); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../libraries/LibDiamondStorage.sol"; import "../interfaces/IDiamondLoupe.sol"; import "../interfaces/IERC165.sol"; contract DiamondLoupeFacet is IDiamondLoupe, IERC165 { // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external override view returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorCount = ds.selectors.length; // create an array set to the maximum size possible facets_ = new Facet[](selectorCount); // create an array for counting the number of selectors for each facet uint8[] memory numFacetSelectors = new uint8[](selectorCount); // total number of facets uint256 numFacets; // loop through function selectors for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) { bytes4 selector = ds.selectors[selectorIndex]; address facetAddress_ = ds.facets[selector].facetAddress; bool continueLoop = false; // find the functionSelectors array for selector and add selector to it for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facets_[facetIndex].facetAddress == facetAddress_) { facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector; // probably will never have more than 256 functions from one facet contract require(numFacetSelectors[facetIndex] < 255); numFacetSelectors[facetIndex]++; continueLoop = true; break; } } // if functionSelectors array exists for selector then continue loop if (continueLoop) { continueLoop = false; continue; } // create a new functionSelectors array for selector facets_[numFacets].facetAddress = facetAddress_; facets_[numFacets].functionSelectors = new bytes4[](selectorCount); facets_[numFacets].functionSelectors[0] = selector; numFacetSelectors[numFacets] = 1; numFacets++; } for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { uint256 numSelectors = numFacetSelectors[facetIndex]; bytes4[] memory selectors = facets_[facetIndex].functionSelectors; // setting the number of selectors assembly { mstore(selectors, numSelectors) } } // setting the number of facets assembly { mstore(facets_, numFacets) } } /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return _facetFunctionSelectors The selectors associated with a facet address. function facetFunctionSelectors(address _facet) external override view returns (bytes4[] memory _facetFunctionSelectors) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorCount = ds.selectors.length; uint256 numSelectors; _facetFunctionSelectors = new bytes4[](selectorCount); // loop through function selectors for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) { bytes4 selector = ds.selectors[selectorIndex]; address facetAddress_ = ds.facets[selector].facetAddress; if (_facet == facetAddress_) { _facetFunctionSelectors[numSelectors] = selector; numSelectors++; } } // Set the number of selectors in the array assembly { mstore(_facetFunctionSelectors, numSelectors) } } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external override view returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorCount = ds.selectors.length; // create an array set to the maximum size possible facetAddresses_ = new address[](selectorCount); uint256 numFacets; // loop through function selectors for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) { bytes4 selector = ds.selectors[selectorIndex]; address facetAddress_ = ds.facets[selector].facetAddress; bool continueLoop = false; // see if we have collected the address already and break out of loop if we have for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facetAddress_ == facetAddresses_[facetIndex]) { continueLoop = true; break; } } // continue loop if we already have the address if (continueLoop) { continueLoop = false; continue; } // include address facetAddresses_[numFacets] = facetAddress_; numFacets++; } // Set the number of facet addresses in the array assembly { mstore(facetAddresses_, numFacets) } } /// @notice Gets the facet address that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external override view returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.facets[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external override view returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../libraries/LibBarnStorage.sol"; import "../libraries/LibOwnership.sol"; contract ChangeRewardsFacet { function changeRewardsAddress(address _rewards) public { LibOwnership.enforceIsContractOwner(); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); ds.rewards = IRewards(_rewards); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IRewards.sol"; library LibBarnStorage { bytes32 constant STORAGE_POSITION = keccak256("com.barnbridge.barn.storage"); struct Checkpoint { uint256 timestamp; uint256 amount; } struct Stake { uint256 timestamp; uint256 amount; uint256 expiryTimestamp; address delegatedTo; } struct Storage { bool initialized; // mapping of user address to history of Stake objects // every user action creates a new object in the history mapping(address => Stake[]) userStakeHistory; // array of bond staked Checkpoint // deposits/withdrawals create a new object in the history (max one per block) Checkpoint[] bondStakedHistory; // mapping of user address to history of delegated power // every delegate/stopDelegate call create a new checkpoint (max one per block) mapping(address => Checkpoint[]) delegatedPowerHistory; IERC20 bond; IRewards rewards; } function barnStorage() internal pure returns (Storage storage ds) { bytes32 position = STORAGE_POSITION; assembly { ds.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface IRewards { function registerUserAction(address user) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "../interfaces/IRewards.sol"; contract BarnMock { IRewards public r; uint256 public bondStaked; mapping(address => uint256) private balances; function setRewards(address rewards) public { r = IRewards(rewards); } function callRegisterUserAction(address user) public { return r.registerUserAction(user); } function deposit(address user, uint256 amount) public { callRegisterUserAction(user); balances[user] = balances[user] + amount; bondStaked = bondStaked + amount; } function withdraw(address user, uint256 amount) public { require(balances[user] >= amount, "insufficient balance"); callRegisterUserAction(user); balances[user] = balances[user] - amount; bondStaked = bondStaked - amount; } function balanceOf(address user) public view returns (uint256) { return balances[user]; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IBarn.sol"; contract Rewards is Ownable { using SafeMath for uint256; uint256 constant decimals = 10 ** 18; struct Pull { address source; uint256 startTs; uint256 endTs; uint256 totalDuration; uint256 totalAmount; } Pull public pullFeature; bool public disabled; uint256 public lastPullTs; uint256 public balanceBefore; uint256 public currentMultiplier; mapping(address => uint256) public userMultiplier; mapping(address => uint256) public owed; IBarn public barn; IERC20 public rewardToken; event Claim(address indexed user, uint256 amount); constructor(address _owner, address _token, address _barn) { require(_token != address(0), "reward token must not be 0x0"); require(_barn != address(0), "barn address must not be 0x0"); transferOwnership(_owner); rewardToken = IERC20(_token); barn = IBarn(_barn); } // registerUserAction is called by the Barn every time the user does a deposit or withdrawal in order to // account for the changes in reward that the user should get // it updates the amount owed to the user without transferring the funds function registerUserAction(address user) public { require(msg.sender == address(barn), 'only callable by barn'); _calculateOwed(user); } // claim calculates the currently owed reward and transfers the funds to the user function claim() public returns (uint256){ _calculateOwed(msg.sender); uint256 amount = owed[msg.sender]; require(amount > 0, "nothing to claim"); owed[msg.sender] = 0; rewardToken.transfer(msg.sender, amount); // acknowledge the amount that was transferred to the user ackFunds(); emit Claim(msg.sender, amount); return amount; } // ackFunds checks the difference between the last known balance of `token` and the current one // if it goes up, the multiplier is re-calculated // if it goes down, it only updates the known balance function ackFunds() public { uint256 balanceNow = rewardToken.balanceOf(address(this)); if (balanceNow == 0 || balanceNow <= balanceBefore) { balanceBefore = balanceNow; return; } uint256 totalStakedBond = barn.bondStaked(); // if there's no bond staked, it doesn't make sense to ackFunds because there's nobody to distribute them to // and the calculation would fail anyways due to division by 0 if (totalStakedBond == 0) { return; } uint256 diff = balanceNow.sub(balanceBefore); uint256 multiplier = currentMultiplier.add(diff.mul(decimals).div(totalStakedBond)); balanceBefore = balanceNow; currentMultiplier = multiplier; } // setupPullToken is used to setup the rewards system; only callable by contract owner // set source to address(0) to disable the functionality function setupPullToken(address source, uint256 startTs, uint256 endTs, uint256 amount) public { require(msg.sender == owner(), "!owner"); require(!disabled, "contract is disabled"); if (pullFeature.source != address(0)) { require(source == address(0), "contract is already set up, source must be 0x0"); disabled = true; } else { require(source != address(0), "contract is not setup, source must be != 0x0"); } if (source == address(0)) { require(startTs == 0, "disable contract: startTs must be 0"); require(endTs == 0, "disable contract: endTs must be 0"); require(amount == 0, "disable contract: amount must be 0"); } else { require(endTs > startTs, "setup contract: endTs must be greater than startTs"); require(amount > 0, "setup contract: amount must be greater than 0"); } pullFeature.source = source; pullFeature.startTs = startTs; pullFeature.endTs = endTs; pullFeature.totalDuration = endTs.sub(startTs); pullFeature.totalAmount = amount; if (lastPullTs < startTs) { lastPullTs = startTs; } } // setBarn sets the address of the BarnBridge Barn into the state variable function setBarn(address _barn) public { require(_barn != address(0), 'barn address must not be 0x0'); require(msg.sender == owner(), '!owner'); barn = IBarn(_barn); } // _pullToken calculates the amount based on the time passed since the last pull relative // to the total amount of time that the pull functionality is active and executes a transferFrom from the // address supplied as `pullTokenFrom`, if enabled function _pullToken() internal { if ( pullFeature.source == address(0) || block.timestamp < pullFeature.startTs ) { return; } uint256 timestampCap = pullFeature.endTs; if (block.timestamp < pullFeature.endTs) { timestampCap = block.timestamp; } if (lastPullTs >= timestampCap) { return; } uint256 timeSinceLastPull = timestampCap.sub(lastPullTs); uint256 shareToPull = timeSinceLastPull.mul(decimals).div(pullFeature.totalDuration); uint256 amountToPull = pullFeature.totalAmount.mul(shareToPull).div(decimals); lastPullTs = block.timestamp; rewardToken.transferFrom(pullFeature.source, address(this), amountToPull); } // _calculateOwed calculates and updates the total amount that is owed to an user and updates the user's multiplier // to the current value // it automatically attempts to pull the token from the source and acknowledge the funds function _calculateOwed(address user) internal { _pullToken(); ackFunds(); uint256 reward = _userPendingReward(user); owed[user] = owed[user].add(reward); userMultiplier[user] = currentMultiplier; } // _userPendingReward calculates the reward that should be based on the current multiplier / anything that's not included in the `owed[user]` value // it does not represent the entire reward that's due to the user unless added on top of `owed[user]` function _userPendingReward(address user) internal view returns (uint256) { uint256 multiplier = currentMultiplier.sub(userMultiplier[user]); return barn.balanceOf(user).mul(multiplier).div(decimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../libraries/LibBarnStorage.sol"; interface IBarn { // deposit allows a user to add more bond to his staked balance function deposit(uint256 amount) external; // withdraw allows a user to withdraw funds if the balance is not locked function withdraw(uint256 amount) external; // lock a user's currently staked balance until timestamp & add the bonus to his voting power function lock(uint256 timestamp) external; // delegate allows a user to delegate his voting power to another user function delegate(address to) external; // stopDelegate allows a user to take back the delegated voting power function stopDelegate() external; // lock the balance of a proposal creator until the voting ends; only callable by DAO function lockCreatorBalance(address user, uint256 timestamp) external; // balanceOf returns the current BOND balance of a user (bonus not included) function balanceOf(address user) external view returns (uint256); // balanceAtTs returns the amount of BOND that the user currently staked (bonus NOT included) function balanceAtTs(address user, uint256 timestamp) external view returns (uint256); // stakeAtTs returns the Stake object of the user that was valid at `timestamp` function stakeAtTs(address user, uint256 timestamp) external view returns (LibBarnStorage.Stake memory); // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block function votingPower(address user) external view returns (uint256); // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // bondStaked returns the total raw amount of BOND staked at the current block function bondStaked() external view returns (uint256); // bondStakedAtTs returns the total raw amount of BOND users have deposited into the contract // it does not include any bonus function bondStakedAtTs(uint256 timestamp) external view returns (uint256); // delegatedPower returns the total voting power that a user received from other users function delegatedPower(address user) external view returns (uint256); // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time function delegatedPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp // it includes the decay mechanism function multiplierAtTs(address user, uint256 timestamp) external view returns (uint256); // userLockedUntil returns the timestamp until the user's balance is locked function userLockedUntil(address user) external view returns (uint256); // userDidDelegate returns the address to which a user delegated their voting power; address(0) if not delegated function userDelegatedTo(address user) external view returns (address); // bondCirculatingSupply returns the current circulating supply of BOND function bondCirculatingSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "../interfaces/IBarn.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MulticallMock { using SafeMath for uint256; IBarn barn; IERC20 bond; constructor(address _barn, address _bond) { barn = IBarn(_barn); bond = IERC20(_bond); } function multiDelegate(uint256 amount, address user1, address user2) public { bond.approve(address(barn), amount); barn.deposit(amount); barn.delegate(user1); barn.delegate(user2); barn.delegate(user1); } function multiDeposit(uint256 amount) public { bond.approve(address(barn), amount.mul(3)); barn.deposit(amount); barn.deposit(amount); barn.deposit(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20("ERC20Mock", "MCK") { bool public transferFromCalled = false; bool public transferCalled = false; address public transferRecipient = address(0); uint256 public transferAmount = 0; function mint(address user, uint256 amount) public { _mint(user, amount); } function burnFrom(address user, uint256 amount) public { _burn(user, amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { transferFromCalled = true; return super.transferFrom(sender, recipient, amount); } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { transferCalled = true; transferRecipient = recipient; transferAmount = amount; return super.transfer(recipient, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/IBarn.sol"; import "../libraries/LibBarnStorage.sol"; import "../libraries/LibOwnership.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract BarnFacet { using SafeMath for uint256; uint256 constant public MAX_LOCK = 365 days; uint256 constant BASE_MULTIPLIER = 1e18; event Deposit(address indexed user, uint256 amount, uint256 newBalance); event Withdraw(address indexed user, uint256 amountWithdrew, uint256 amountLeft); event Lock(address indexed user, uint256 timestamp); event Delegate(address indexed from, address indexed to); event DelegatedPowerIncreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower); event DelegatedPowerDecreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower); function initBarn(address _bond, address _rewards) public { require(_bond != address(0), "BOND address must not be 0x0"); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); require(!ds.initialized, "Barn: already initialized"); LibOwnership.enforceIsContractOwner(); ds.initialized = true; ds.bond = IERC20(_bond); ds.rewards = IRewards(_rewards); } // deposit allows a user to add more bond to his staked balance function deposit(uint256 amount) public { require(amount > 0, "Amount must be greater than 0"); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); uint256 allowance = ds.bond.allowance(msg.sender, address(this)); require(allowance >= amount, "Token allowance too small"); // this must be called before the user's balance is updated so the rewards contract can calculate // the amount owed correctly if (address(ds.rewards) != address(0)) { ds.rewards.registerUserAction(msg.sender); } uint256 newBalance = balanceOf(msg.sender).add(amount); _updateUserBalance(ds.userStakeHistory[msg.sender], newBalance); _updateLockedBond(bondStakedAtTs(block.timestamp).add(amount)); address delegatedTo = userDelegatedTo(msg.sender); if (delegatedTo != address(0)) { uint256 newDelegatedPower = delegatedPower(delegatedTo).add(amount); _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower); emit DelegatedPowerIncreased(msg.sender, delegatedTo, amount, newDelegatedPower); } ds.bond.transferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount, newBalance); } // withdraw allows a user to withdraw funds if the balance is not locked function withdraw(uint256 amount) public { require(amount > 0, "Amount must be greater than 0"); require(userLockedUntil(msg.sender) <= block.timestamp, "User balance is locked"); uint256 balance = balanceOf(msg.sender); require(balance >= amount, "Insufficient balance"); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); // this must be called before the user's balance is updated so the rewards contract can calculate // the amount owed correctly if (address(ds.rewards) != address(0)) { ds.rewards.registerUserAction(msg.sender); } _updateUserBalance(ds.userStakeHistory[msg.sender], balance.sub(amount)); _updateLockedBond(bondStakedAtTs(block.timestamp).sub(amount)); address delegatedTo = userDelegatedTo(msg.sender); if (delegatedTo != address(0)) { uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(amount); _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower); emit DelegatedPowerDecreased(msg.sender, delegatedTo, amount, newDelegatedPower); } ds.bond.transfer(msg.sender, amount); emit Withdraw(msg.sender, amount, balance.sub(amount)); } // lock a user's currently staked balance until timestamp & add the bonus to his voting power function lock(uint256 timestamp) public { require(timestamp > block.timestamp, "Timestamp must be in the future"); require(timestamp <= block.timestamp + MAX_LOCK, "Timestamp too big"); require(balanceOf(msg.sender) > 0, "Sender has no balance"); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); LibBarnStorage.Stake[] storage checkpoints = ds.userStakeHistory[msg.sender]; LibBarnStorage.Stake storage currentStake = checkpoints[checkpoints.length - 1]; require(timestamp > currentStake.expiryTimestamp, "New timestamp lower than current lock timestamp"); _updateUserLock(checkpoints, timestamp); emit Lock(msg.sender, timestamp); } function depositAndLock(uint256 amount, uint256 timestamp) public { deposit(amount); lock(timestamp); } // delegate allows a user to delegate his voting power to another user function delegate(address to) public { require(msg.sender != to, "Can't delegate to self"); uint256 senderBalance = balanceOf(msg.sender); require(senderBalance > 0, "No balance to delegate"); LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); emit Delegate(msg.sender, to); address delegatedTo = userDelegatedTo(msg.sender); if (delegatedTo != address(0)) { uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(senderBalance); _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower); emit DelegatedPowerDecreased(msg.sender, delegatedTo, senderBalance, newDelegatedPower); } if (to != address(0)) { uint256 newDelegatedPower = delegatedPower(to).add(senderBalance); _updateDelegatedPower(ds.delegatedPowerHistory[to], newDelegatedPower); emit DelegatedPowerIncreased(msg.sender, to, senderBalance, newDelegatedPower); } _updateUserDelegatedTo(ds.userStakeHistory[msg.sender], to); } // stopDelegate allows a user to take back the delegated voting power function stopDelegate() public { return delegate(address(0)); } // balanceOf returns the current BOND balance of a user (bonus not included) function balanceOf(address user) public view returns (uint256) { return balanceAtTs(user, block.timestamp); } // balanceAtTs returns the amount of BOND that the user currently staked (bonus NOT included) function balanceAtTs(address user, uint256 timestamp) public view returns (uint256) { LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp); return stake.amount; } // stakeAtTs returns the Stake object of the user that was valid at `timestamp` function stakeAtTs(address user, uint256 timestamp) public view returns (LibBarnStorage.Stake memory) { LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); LibBarnStorage.Stake[] storage stakeHistory = ds.userStakeHistory[user]; if (stakeHistory.length == 0 || timestamp < stakeHistory[0].timestamp) { return LibBarnStorage.Stake(block.timestamp, 0, block.timestamp, address(0)); } uint256 min = 0; uint256 max = stakeHistory.length - 1; if (timestamp >= stakeHistory[max].timestamp) { return stakeHistory[max]; } // binary search of the value in the array while (max > min) { uint256 mid = (max + min + 1) / 2; if (stakeHistory[mid].timestamp <= timestamp) { min = mid; } else { max = mid - 1; } } return stakeHistory[min]; } // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block function votingPower(address user) public view returns (uint256) { return votingPowerAtTs(user, block.timestamp); } // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time function votingPowerAtTs(address user, uint256 timestamp) public view returns (uint256) { LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp); uint256 ownVotingPower; // if the user delegated his voting power to another user, then he doesn't have any voting power left if (stake.delegatedTo != address(0)) { ownVotingPower = 0; } else { uint256 balance = stake.amount; uint256 multiplier = _stakeMultiplier(stake, timestamp); ownVotingPower = balance.mul(multiplier).div(BASE_MULTIPLIER); } uint256 delegatedVotingPower = delegatedPowerAtTs(user, timestamp); return ownVotingPower.add(delegatedVotingPower); } // bondStaked returns the total raw amount of BOND staked at the current block function bondStaked() public view returns (uint256) { return bondStakedAtTs(block.timestamp); } // bondStakedAtTs returns the total raw amount of BOND users have deposited into the contract // it does not include any bonus function bondStakedAtTs(uint256 timestamp) public view returns (uint256) { return _checkpointsBinarySearch(LibBarnStorage.barnStorage().bondStakedHistory, timestamp); } // delegatedPower returns the total voting power that a user received from other users function delegatedPower(address user) public view returns (uint256) { return delegatedPowerAtTs(user, block.timestamp); } // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time function delegatedPowerAtTs(address user, uint256 timestamp) public view returns (uint256) { return _checkpointsBinarySearch(LibBarnStorage.barnStorage().delegatedPowerHistory[user], timestamp); } // same as multiplierAtTs but for the current block timestamp function multiplierOf(address user) public view returns (uint256) { return multiplierAtTs(user, block.timestamp); } // multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp // it includes the decay mechanism function multiplierAtTs(address user, uint256 timestamp) public view returns (uint256) { LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp); return _stakeMultiplier(stake, timestamp); } // userLockedUntil returns the timestamp until the user's balance is locked function userLockedUntil(address user) public view returns (uint256) { LibBarnStorage.Stake memory c = stakeAtTs(user, block.timestamp); return c.expiryTimestamp; } // userDelegatedTo returns the address to which a user delegated their voting power; address(0) if not delegated function userDelegatedTo(address user) public view returns (address) { LibBarnStorage.Stake memory c = stakeAtTs(user, block.timestamp); return c.delegatedTo; } // _checkpointsBinarySearch executes a binary search on a list of checkpoints that's sorted chronologically // looking for the closest checkpoint that matches the specified timestamp function _checkpointsBinarySearch(LibBarnStorage.Checkpoint[] storage checkpoints, uint256 timestamp) internal view returns (uint256) { if (checkpoints.length == 0 || timestamp < checkpoints[0].timestamp) { return 0; } uint256 min = 0; uint256 max = checkpoints.length - 1; if (timestamp >= checkpoints[max].timestamp) { return checkpoints[max].amount; } // binary search of the value in the array while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].timestamp <= timestamp) { min = mid; } else { max = mid - 1; } } return checkpoints[min].amount; } // _stakeMultiplier calculates the multiplier for the given stake at the given timestamp function _stakeMultiplier(LibBarnStorage.Stake memory stake, uint256 timestamp) internal view returns (uint256) { if (timestamp >= stake.expiryTimestamp) { return BASE_MULTIPLIER; } uint256 diff = stake.expiryTimestamp - timestamp; if (diff >= MAX_LOCK) { return BASE_MULTIPLIER.mul(2); } return BASE_MULTIPLIER.add(diff.mul(BASE_MULTIPLIER).div(MAX_LOCK)); } // _updateUserBalance manages an array of checkpoints // if there's already a checkpoint for the same timestamp, the amount is updated // otherwise, a new checkpoint is inserted function _updateUserBalance(LibBarnStorage.Stake[] storage checkpoints, uint256 amount) internal { if (checkpoints.length == 0) { checkpoints.push(LibBarnStorage.Stake(block.timestamp, amount, block.timestamp, address(0))); } else { LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1]; if (old.timestamp == block.timestamp) { old.amount = amount; } else { checkpoints.push(LibBarnStorage.Stake(block.timestamp, amount, old.expiryTimestamp, old.delegatedTo)); } } } // _updateUserLock updates the expiry timestamp on the user's stake // it assumes that if the user already has a balance, which is checked for in the lock function // then there must be at least 1 checkpoint function _updateUserLock(LibBarnStorage.Stake[] storage checkpoints, uint256 expiryTimestamp) internal { LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1]; if (old.timestamp < block.timestamp) { checkpoints.push(LibBarnStorage.Stake(block.timestamp, old.amount, expiryTimestamp, old.delegatedTo)); } else { old.expiryTimestamp = expiryTimestamp; } } // _updateUserDelegatedTo updates the delegateTo property on the user's stake // it assumes that if the user already has a balance, which is checked for in the delegate function // then there must be at least 1 checkpoint function _updateUserDelegatedTo(LibBarnStorage.Stake[] storage checkpoints, address to) internal { LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1]; if (old.timestamp < block.timestamp) { checkpoints.push(LibBarnStorage.Stake(block.timestamp, old.amount, old.expiryTimestamp, to)); } else { old.delegatedTo = to; } } // _updateDelegatedPower updates the power delegated TO the user in the checkpoints history function _updateDelegatedPower(LibBarnStorage.Checkpoint[] storage checkpoints, uint256 amount) internal { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].timestamp < block.timestamp) { checkpoints.push(LibBarnStorage.Checkpoint(block.timestamp, amount)); } else { LibBarnStorage.Checkpoint storage old = checkpoints[checkpoints.length - 1]; old.amount = amount; } } // _updateLockedBond stores the new `amount` into the BOND locked history function _updateLockedBond(uint256 amount) internal { LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage(); if (ds.bondStakedHistory.length == 0 || ds.bondStakedHistory[ds.bondStakedHistory.length - 1].timestamp < block.timestamp) { ds.bondStakedHistory.push(LibBarnStorage.Checkpoint(block.timestamp, amount)); } else { LibBarnStorage.Checkpoint storage old = ds.bondStakedHistory[ds.bondStakedHistory.length - 1]; old.amount = amount; } } }
ERC-173 Contract Ownership Standard Note: the ERC-165 identifier for this interface is 0x7f5828d0 is ERC165 /
interface IERC173 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() external view returns (address owner_); function transferOwnership(address _newOwner) external; } pragma solidity 0.7.6; }
607,705
// Verified using https://dapp.tools // hevm: flattened sources of /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/SurplusAuctionHouse.sol pragma solidity =0.6.7; ////// /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/SurplusAuctionHouse.sol /// SurplusAuctionHouse.sol // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.6.7; */ abstract contract SAFEEngineLike_11 { function transferInternalCoins(address,address,uint256) virtual external; function coinBalance(address) virtual external view returns (uint256); function approveSAFEModification(address) virtual external; function denySAFEModification(address) virtual external; } abstract contract TokenLike_2 { function approve(address, uint256) virtual public returns (bool); function balanceOf(address) virtual public view returns (uint256); function move(address,address,uint256) virtual external; function burn(address,uint256) virtual external; } /* This thing lets you auction some system coins in return for protocol tokens that are then burnt */ contract BurningSurplusAuctionHouse { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "BurningSurplusAuctionHouse/account-not-authorized"); _; } // --- Data --- struct Bid { // Bid size (how many protocol tokens are offered per system coins sold) uint256 bidAmount; // [wad] // How many system coins are sold in an auction uint256 amountToSell; // [rad] // Who the high bidder is address highBidder; // When the latest bid expires and the auction can be settled uint48 bidExpiry; // [unix epoch time] // Hard deadline for the auction after which no more bids can be placed uint48 auctionDeadline; // [unix epoch time] } // Bid data for each separate auction mapping (uint256 => Bid) public bids; // SAFE database SAFEEngineLike_11 public safeEngine; // Protocol token address TokenLike_2 public protocolToken; uint256 constant ONE = 1.00E18; // [wad] // Minimum bid increase compared to the last bid in order to take the new one in consideration uint256 public bidIncrease = 1.05E18; // [wad] // How long the auction lasts after a new bid is submitted uint48 public bidDuration = 3 hours; // [seconds] // Total length of the auction uint48 public totalAuctionLength = 2 days; // [seconds] // Number of auctions started up until now uint256 public auctionsStarted = 0; // Whether the contract is settled or not uint256 public contractEnabled; bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("SURPLUS"); bytes32 public constant SURPLUS_AUCTION_TYPE = bytes32("BURNING"); // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint256 data); event RestartAuction(uint256 id, uint256 auctionDeadline); event IncreaseBidSize(uint256 id, address highBidder, uint256 amountToBuy, uint256 bid, uint256 bidExpiry); event StartAuction( uint256 indexed id, uint256 auctionsStarted, uint256 amountToSell, uint256 initialBid, uint256 auctionDeadline ); event SettleAuction(uint256 indexed id); event DisableContract(); event TerminateAuctionPrematurely(uint256 indexed id, address sender, address highBidder, uint256 bidAmount); // --- Init --- constructor(address safeEngine_, address protocolToken_) public { require(safeEngine_ != address(0), "BurningSurplusAuctionHouse/safe-engine-address-invalid"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike_11(safeEngine_); protocolToken = TokenLike_2(protocolToken_); contractEnabled = 1; emit AddAuthorization(msg.sender); } // --- Math --- function addUint48(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x, "BurningSurplusAuctionHouse/add-uint48-overflow"); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "BurningSurplusAuctionHouse/mul-overflow"); } // --- Admin --- /** * @notice Modify auction parameters * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "bidIncrease") bidIncrease = data; else if (parameter == "bidDuration") bidDuration = uint48(data); else if (parameter == "totalAuctionLength") totalAuctionLength = uint48(data); else revert("BurningSurplusAuctionHouse/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Auction --- /** * @notice Start a new surplus auction * @param amountToSell Total amount of system coins to sell (rad) * @param initialBid Initial protocol token bid (wad) */ function startAuction(uint256 amountToSell, uint256 initialBid) external isAuthorized returns (uint256 id) { require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled"); require(auctionsStarted < uint256(-1), "BurningSurplusAuctionHouse/overflow"); id = ++auctionsStarted; bids[id].bidAmount = initialBid; bids[id].amountToSell = amountToSell; bids[id].highBidder = msg.sender; bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); safeEngine.transferInternalCoins(msg.sender, address(this), amountToSell); emit StartAuction(id, auctionsStarted, amountToSell, initialBid, bids[id].auctionDeadline); } /** * @notice Restart an auction if no bids were submitted for it * @param id ID of the auction to restart */ function restartAuction(uint256 id) external { require(bids[id].auctionDeadline < now, "BurningSurplusAuctionHouse/not-finished"); require(bids[id].bidExpiry == 0, "BurningSurplusAuctionHouse/bid-already-placed"); bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); emit RestartAuction(id, bids[id].auctionDeadline); } /** * @notice Submit a higher protocol token bid for the same amount of system coins * @param id ID of the auction you want to submit the bid for * @param amountToBuy Amount of system coins to buy (rad) * @param bid New bid submitted (wad) */ function increaseBidSize(uint256 id, uint256 amountToBuy, uint256 bid) external { require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled"); require(bids[id].highBidder != address(0), "BurningSurplusAuctionHouse/high-bidder-not-set"); require(bids[id].bidExpiry > now || bids[id].bidExpiry == 0, "BurningSurplusAuctionHouse/bid-already-expired"); require(bids[id].auctionDeadline > now, "BurningSurplusAuctionHouse/auction-already-expired"); require(amountToBuy == bids[id].amountToSell, "BurningSurplusAuctionHouse/amounts-not-matching"); require(bid > bids[id].bidAmount, "BurningSurplusAuctionHouse/bid-not-higher"); require(multiply(bid, ONE) >= multiply(bidIncrease, bids[id].bidAmount), "BurningSurplusAuctionHouse/insufficient-increase"); if (msg.sender != bids[id].highBidder) { protocolToken.move(msg.sender, bids[id].highBidder, bids[id].bidAmount); bids[id].highBidder = msg.sender; } protocolToken.move(msg.sender, address(this), bid - bids[id].bidAmount); bids[id].bidAmount = bid; bids[id].bidExpiry = addUint48(uint48(now), bidDuration); emit IncreaseBidSize(id, msg.sender, amountToBuy, bid, bids[id].bidExpiry); } /** * @notice Settle/finish an auction * @param id ID of the auction to settle */ function settleAuction(uint256 id) external { require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled"); require(bids[id].bidExpiry != 0 && (bids[id].bidExpiry < now || bids[id].auctionDeadline < now), "BurningSurplusAuctionHouse/not-finished"); safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].amountToSell); protocolToken.burn(address(this), bids[id].bidAmount); delete bids[id]; emit SettleAuction(id); } /** * @notice Disable the auction house (usually called by AccountingEngine) **/ function disableContract() external isAuthorized { contractEnabled = 0; safeEngine.transferInternalCoins(address(this), msg.sender, safeEngine.coinBalance(address(this))); emit DisableContract(); } /** * @notice Terminate an auction prematurely. * @param id ID of the auction to settle/terminate */ function terminateAuctionPrematurely(uint256 id) external { require(contractEnabled == 0, "BurningSurplusAuctionHouse/contract-still-enabled"); require(bids[id].highBidder != address(0), "BurningSurplusAuctionHouse/high-bidder-not-set"); protocolToken.move(address(this), bids[id].highBidder, bids[id].bidAmount); emit TerminateAuctionPrematurely(id, msg.sender, bids[id].highBidder, bids[id].bidAmount); delete bids[id]; } } // This thing lets you auction surplus for protocol tokens that are then sent to another address contract RecyclingSurplusAuctionHouse { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "RecyclingSurplusAuctionHouse/account-not-authorized"); _; } // --- Data --- struct Bid { // Bid size (how many protocol tokens are offered per system coins sold) uint256 bidAmount; // [wad] // How many system coins are sold in an auction uint256 amountToSell; // [rad] // Who the high bidder is address highBidder; // When the latest bid expires and the auction can be settled uint48 bidExpiry; // [unix epoch time] // Hard deadline for the auction after which no more bids can be placed uint48 auctionDeadline; // [unix epoch time] } // Bid data for each separate auction mapping (uint256 => Bid) public bids; // SAFE database SAFEEngineLike_11 public safeEngine; // Protocol token address TokenLike_2 public protocolToken; // Receiver of protocol tokens address public protocolTokenBidReceiver; uint256 constant ONE = 1.00E18; // [wad] // Minimum bid increase compared to the last bid in order to take the new one in consideration uint256 public bidIncrease = 1.05E18; // [wad] // How long the auction lasts after a new bid is submitted uint48 public bidDuration = 3 hours; // [seconds] // Total length of the auction uint48 public totalAuctionLength = 2 days; // [seconds] // Number of auctions started up until now uint256 public auctionsStarted = 0; // Whether the contract is settled or not uint256 public contractEnabled; bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("SURPLUS"); bytes32 public constant SURPLUS_AUCTION_TYPE = bytes32("RECYCLING"); // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint256 data); event ModifyParameters(bytes32 parameter, address addr); event RestartAuction(uint256 id, uint256 auctionDeadline); event IncreaseBidSize(uint256 id, address highBidder, uint256 amountToBuy, uint256 bid, uint256 bidExpiry); event StartAuction( uint256 indexed id, uint256 auctionsStarted, uint256 amountToSell, uint256 initialBid, uint256 auctionDeadline ); event SettleAuction(uint256 indexed id); event DisableContract(); event TerminateAuctionPrematurely(uint256 indexed id, address sender, address highBidder, uint256 bidAmount); // --- Init --- constructor(address safeEngine_, address protocolToken_) public { require(safeEngine_ != address(0), "RecyclingSurplusAuctionHouse/safe-engine-address-invalid"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike_11(safeEngine_); protocolToken = TokenLike_2(protocolToken_); contractEnabled = 1; emit AddAuthorization(msg.sender); } // --- Math --- function addUint48(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x, "RecyclingSurplusAuctionHouse/add-uint48-overflow"); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "RecyclingSurplusAuctionHouse/mul-overflow"); } // --- Admin --- /** * @notice Modify uint256 parameters * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "bidIncrease") bidIncrease = data; else if (parameter == "bidDuration") bidDuration = uint48(data); else if (parameter == "totalAuctionLength") totalAuctionLength = uint48(data); else revert("RecyclingSurplusAuctionHouse/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify address parameters * @param parameter The name of the parameter modified * @param addr New address value */ function modifyParameters(bytes32 parameter, address addr) external isAuthorized { require(addr != address(0), "RecyclingSurplusAuctionHouse/invalid-address"); if (parameter == "protocolTokenBidReceiver") protocolTokenBidReceiver = addr; else revert("RecyclingSurplusAuctionHouse/modify-unrecognized-param"); emit ModifyParameters(parameter, addr); } // --- Auction --- /** * @notice Start a new surplus auction * @param amountToSell Total amount of system coins to sell (rad) * @param initialBid Initial protocol token bid (wad) */ function startAuction(uint256 amountToSell, uint256 initialBid) external isAuthorized returns (uint256 id) { require(contractEnabled == 1, "RecyclingSurplusAuctionHouse/contract-not-enabled"); require(auctionsStarted < uint256(-1), "RecyclingSurplusAuctionHouse/overflow"); require(protocolTokenBidReceiver != address(0), "RecyclingSurplusAuctionHouse/null-prot-token-receiver"); id = ++auctionsStarted; bids[id].bidAmount = initialBid; bids[id].amountToSell = amountToSell; bids[id].highBidder = msg.sender; bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); safeEngine.transferInternalCoins(msg.sender, address(this), amountToSell); emit StartAuction(id, auctionsStarted, amountToSell, initialBid, bids[id].auctionDeadline); } /** * @notice Restart an auction if no bids were submitted for it * @param id ID of the auction to restart */ function restartAuction(uint256 id) external { require(bids[id].auctionDeadline < now, "RecyclingSurplusAuctionHouse/not-finished"); require(bids[id].bidExpiry == 0, "RecyclingSurplusAuctionHouse/bid-already-placed"); bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); emit RestartAuction(id, bids[id].auctionDeadline); } /** * @notice Submit a higher protocol token bid for the same amount of system coins * @param id ID of the auction you want to submit the bid for * @param amountToBuy Amount of system coins to buy (rad) * @param bid New bid submitted (wad) */ function increaseBidSize(uint256 id, uint256 amountToBuy, uint256 bid) external { require(contractEnabled == 1, "RecyclingSurplusAuctionHouse/contract-not-enabled"); require(bids[id].highBidder != address(0), "RecyclingSurplusAuctionHouse/high-bidder-not-set"); require(bids[id].bidExpiry > now || bids[id].bidExpiry == 0, "RecyclingSurplusAuctionHouse/bid-already-expired"); require(bids[id].auctionDeadline > now, "RecyclingSurplusAuctionHouse/auction-already-expired"); require(amountToBuy == bids[id].amountToSell, "RecyclingSurplusAuctionHouse/amounts-not-matching"); require(bid > bids[id].bidAmount, "RecyclingSurplusAuctionHouse/bid-not-higher"); require(multiply(bid, ONE) >= multiply(bidIncrease, bids[id].bidAmount), "RecyclingSurplusAuctionHouse/insufficient-increase"); if (msg.sender != bids[id].highBidder) { protocolToken.move(msg.sender, bids[id].highBidder, bids[id].bidAmount); bids[id].highBidder = msg.sender; } protocolToken.move(msg.sender, address(this), bid - bids[id].bidAmount); bids[id].bidAmount = bid; bids[id].bidExpiry = addUint48(uint48(now), bidDuration); emit IncreaseBidSize(id, msg.sender, amountToBuy, bid, bids[id].bidExpiry); } /** * @notice Settle/finish an auction * @param id ID of the auction to settle */ function settleAuction(uint256 id) external { require(contractEnabled == 1, "RecyclingSurplusAuctionHouse/contract-not-enabled"); require(bids[id].bidExpiry != 0 && (bids[id].bidExpiry < now || bids[id].auctionDeadline < now), "RecyclingSurplusAuctionHouse/not-finished"); safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].amountToSell); protocolToken.move(address(this), protocolTokenBidReceiver, bids[id].bidAmount); delete bids[id]; emit SettleAuction(id); } /** * @notice Disable the auction house (usually called by AccountingEngine) **/ function disableContract() external isAuthorized { contractEnabled = 0; safeEngine.transferInternalCoins(address(this), msg.sender, safeEngine.coinBalance(address(this))); emit DisableContract(); } /** * @notice Terminate an auction prematurely. * @param id ID of the auction to settle/terminate */ function terminateAuctionPrematurely(uint256 id) external { require(contractEnabled == 0, "RecyclingSurplusAuctionHouse/contract-still-enabled"); require(bids[id].highBidder != address(0), "RecyclingSurplusAuctionHouse/high-bidder-not-set"); protocolToken.move(address(this), bids[id].highBidder, bids[id].bidAmount); emit TerminateAuctionPrematurely(id, msg.sender, bids[id].highBidder, bids[id].bidAmount); delete bids[id]; } } contract PostSettlementSurplusAuctionHouse { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "PostSettlementSurplusAuctionHouse/account-not-authorized"); _; } // --- Data --- struct Bid { // Bid size (how many protocol tokens are offered per system coins sold) uint256 bidAmount; // [rad] // How many system coins are sold in an auction uint256 amountToSell; // [wad] // Who the high bidder is address highBidder; // When the latest bid expires and the auction can be settled uint48 bidExpiry; // [unix epoch time] // Hard deadline for the auction after which no more bids can be placed uint48 auctionDeadline; // [unix epoch time] } // Bid data for each separate auction mapping (uint256 => Bid) public bids; // SAFE database SAFEEngineLike_11 public safeEngine; // Protocol token address TokenLike_2 public protocolToken; uint256 constant ONE = 1.00E18; // [wad] // Minimum bid increase compared to the last bid in order to take the new one in consideration uint256 public bidIncrease = 1.05E18; // [wad] // How long the auction lasts after a new bid is submitted uint48 public bidDuration = 3 hours; // [seconds] // Total length of the auction uint48 public totalAuctionLength = 2 days; // [seconds] // Number of auctions started up until now uint256 public auctionsStarted = 0; bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("SURPLUS"); // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint256 data); event RestartAuction(uint256 indexed id, uint256 auctionDeadline); event IncreaseBidSize(uint256 indexed id, address highBidder, uint256 amountToBuy, uint256 bid, uint256 bidExpiry); event StartAuction( uint256 indexed id, uint256 auctionsStarted, uint256 amountToSell, uint256 initialBid, uint256 auctionDeadline ); event SettleAuction(uint256 indexed id); // --- Init --- constructor(address safeEngine_, address protocolToken_) public { require(safeEngine_ != address(0), "PostSettlementSurplusAuctionHouse/safe-engine-address-invalid"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike_11(safeEngine_); protocolToken = TokenLike_2(protocolToken_); emit AddAuthorization(msg.sender); } // --- Math --- function addUint48(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } // --- Admin --- /** * @notice Modify uint256 parameters * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "bidIncrease") bidIncrease = data; else if (parameter == "bidDuration") bidDuration = uint48(data); else if (parameter == "totalAuctionLength") totalAuctionLength = uint48(data); else revert("PostSettlementSurplusAuctionHouse/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Auction --- /** * @notice Start a new surplus auction * @param amountToSell Total amount of system coins to sell (wad) * @param initialBid Initial protocol token bid (rad) */ function startAuction(uint256 amountToSell, uint256 initialBid) external isAuthorized returns (uint256 id) { require(auctionsStarted < uint256(-1), "PostSettlementSurplusAuctionHouse/overflow"); id = ++auctionsStarted; bids[id].bidAmount = initialBid; bids[id].amountToSell = amountToSell; bids[id].highBidder = msg.sender; bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); safeEngine.transferInternalCoins(msg.sender, address(this), amountToSell); emit StartAuction(id, auctionsStarted, amountToSell, initialBid, bids[id].auctionDeadline); } /** * @notice Restart an auction if no bids were submitted for it * @param id ID of the auction to restart */ function restartAuction(uint256 id) external { require(bids[id].auctionDeadline < now, "PostSettlementSurplusAuctionHouse/not-finished"); require(bids[id].bidExpiry == 0, "PostSettlementSurplusAuctionHouse/bid-already-placed"); bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); emit RestartAuction(id, bids[id].auctionDeadline); } /** * @notice Submit a higher protocol token bid for the same amount of system coins * @param id ID of the auction you want to submit the bid for * @param amountToBuy Amount of system coins to buy (wad) * @param bid New bid submitted (rad) */ function increaseBidSize(uint256 id, uint256 amountToBuy, uint256 bid) external { require(bids[id].highBidder != address(0), "PostSettlementSurplusAuctionHouse/high-bidder-not-set"); require(bids[id].bidExpiry > now || bids[id].bidExpiry == 0, "PostSettlementSurplusAuctionHouse/bid-already-expired"); require(bids[id].auctionDeadline > now, "PostSettlementSurplusAuctionHouse/auction-already-expired"); require(amountToBuy == bids[id].amountToSell, "PostSettlementSurplusAuctionHouse/amounts-not-matching"); require(bid > bids[id].bidAmount, "PostSettlementSurplusAuctionHouse/bid-not-higher"); require(multiply(bid, ONE) >= multiply(bidIncrease, bids[id].bidAmount), "PostSettlementSurplusAuctionHouse/insufficient-increase"); if (msg.sender != bids[id].highBidder) { protocolToken.move(msg.sender, bids[id].highBidder, bids[id].bidAmount); bids[id].highBidder = msg.sender; } protocolToken.move(msg.sender, address(this), bid - bids[id].bidAmount); bids[id].bidAmount = bid; bids[id].bidExpiry = addUint48(uint48(now), bidDuration); emit IncreaseBidSize(id, msg.sender, amountToBuy, bid, bids[id].bidExpiry); } /** * @notice Settle/finish an auction * @param id ID of the auction to settle */ function settleAuction(uint256 id) external { require(bids[id].bidExpiry != 0 && (bids[id].bidExpiry < now || bids[id].auctionDeadline < now), "PostSettlementSurplusAuctionHouse/not-finished"); safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].amountToSell); protocolToken.burn(address(this), bids[id].bidAmount); delete bids[id]; emit SettleAuction(id); } }
--- Auction --- Start a new surplus auction amountToSell Total amount of system coins to sell (wad) initialBid Initial protocol token bid (rad)/
function startAuction(uint256 amountToSell, uint256 initialBid) external isAuthorized returns (uint256 id) { require(auctionsStarted < uint256(-1), "PostSettlementSurplusAuctionHouse/overflow"); id = ++auctionsStarted; bids[id].bidAmount = initialBid; bids[id].amountToSell = amountToSell; bids[id].highBidder = msg.sender; bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength); safeEngine.transferInternalCoins(msg.sender, address(this), amountToSell); emit StartAuction(id, auctionsStarted, amountToSell, initialBid, bids[id].auctionDeadline); }
6,863,373
./full_match/42/0xA59195b0b7F7137CAe79383c428A6d7Af25F8229/sources/CryptoRockSpawner.sol
Returns whether the option ID can be minted. Can return false if the developer wishes to restrict a total supply per option ID (or overall)./
function canMint(uint256 _blockNumber, uint256 _amount) public view override returns (bool) { (bool _s, uint256 subResult) = block.number.trySub(ROCK_LIFESPAN_BLOCKS); require(_s, "Block life not in range"); if (_blockNumber > block.number || _blockNumber < subResult || _amount > 1) { return false; } return blockNumberToRockNumber[_blockNumber] == 0; }
9,566,947
// SPDX-License-Identifier: MIT pragma solidity ^0.5.15; interface IERC20 { function totalSupply() external view returns (uint256); // 总供应 function balanceOf(address account) external view returns (uint256); // 平衡 function transfer(address recipient, uint256 amount) external returns (bool); // 转让 function allowance(address owner, address spender) external view returns (uint256); // 补助 function approve(address spender, uint256 amount) external returns (bool); // 批准 function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); // 转移自 event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 策略合约的接口层 interface Strategy { function want() external view returns (address); function deposit() external; function withdraw(address) external; function withdraw(uint) external; function withdrawAll() external returns (uint); function balanceOf() external view returns (uint); } // 转换器接口层 interface Converter { function convert(address) external returns (uint); } // 价格交换协议 interface OneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns(uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns( uint256 returnAmount, uint256[] memory distribution ); } contract Controller { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // 给合约中的uint256类型的变量绑定SafeMath库中的所有方法 address public governance; // 治理地址 address public onesplit; // 价格交换协议地址 address public rewards; // 奖励地址 address public burn; // 燃烧地址 address public factory; mapping(address => address) public vaults; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; uint public split = 5000; uint public constant max = 10000; constructor() public { governance = tx.origin; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); rewards = 0xd951aC97Fe2EC2433789A9EC28255C37E0523b46; burn = 0xd951aC97Fe2EC2433789A9EC28255C37E0523b46; } function setFactory(address _factory) public { require(msg.sender == governance, "!governance"); factory = _factory; } function setSplit(uint _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setVault(address _token, address _vault) public { require(msg.sender == governance, "!governance"); vaults[_token] = _vault; } function setConverter(address _input, address _output, address _converter) public { require(msg.sender == governance, "!governance"); converters[_input][_output] = _converter; } function setStrategy(address _token, address _strategy) public { // 某个币对应一个策略, 比如现在的weth就是挖yf require(msg.sender == governance, "!governance"); address _current = strategies[_token]; if (_current != address(0)) { // 之前的策略存在的话,那么就先提取所有资金 Strategy(_current).withdrawAll(); } strategies[_token] = _strategy; } // 抵押代币给Strategy合约进行理财 function earn(address _token, uint _amount) public { address _strategy = strategies[_token]; // 获取策略的合约地址 address _want = Strategy(_strategy).want(); // 策略需要的token地址 if (_want != _token) { // 如果策略需要的和输入的不一样,需要先转换 address converter = converters[_token][_want]; // 转换器合约地址 IERC20(_token).safeTransfer(converter, _amount); // 给转换器打钱 _amount = Converter(converter).convert(_strategy); // 执行转换... IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } Strategy(_strategy).deposit(); // 存钱 } function balanceOf(address _token) external view returns (uint) { return Strategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require(msg.sender == governance, "!governance"); Strategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint _amount) public { // 转任意erc20 token require(msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(governance, _amount); } function getExpectedReturn(address _strategy, address _token, uint parts) public view returns (uint expected) { uint _balance = IERC20(_token).balanceOf(_strategy); // 获取策略器中某个代币的余额 address _want = Strategy(_strategy).want(); // 策略器需要的代币 (expected,) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn(address _strategy, address _token, uint parts) public { // This contract should never have value in it, but just incase since this is a public call uint _before = IERC20(_token).balanceOf(address(this)); // 取出之前的token余额 Strategy(_strategy).withdraw(_token); // 取出token uint _after = IERC20(_token).balanceOf(address(this)); // 取出之后的token余额 if (_after > _before) { uint _amount = _after.sub(_before); address _want = Strategy(_strategy).want(); uint[] memory _distribution; uint _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint _reward = _amount.mul(split).div(max); earn(_want, _amount.sub(_reward)); IERC20(_want).safeTransfer(rewards, _reward); } } } // 去strategy中取款 function withdraw(address _token, uint _amount) public { require(msg.sender == vaults[_token], "!vault"); Strategy(strategies[_token]).withdraw(_amount); } }
抵押代币给Strategy合约进行理财
function earn(address _token, uint _amount) public { IERC20(_want).safeTransfer(_strategy, _amount); IERC20(_token).safeTransfer(_strategy, _amount); } else { }
14,361,494
./full_match/43113/0x85197B93cE10640d2Cd69f3F59c3866A8E351ee4/sources/contracts/chefhaunted.sol
View function to see pending HAUNTED on frontend.
function pendingHAUNTED(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHAUNTEDPerShare = pool.accHAUNTEDPerShare; if (block.timestamp > pool.lastRewardTimestamp && pool.lpSupply != 0 && totalAllocPoint > 0) { uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 HAUNTEDReward = multiplier.mul(HAUNTEDPerSec).mul(pool.allocPoint).div(totalAllocPoint); accHAUNTEDPerShare = accHAUNTEDPerShare.add(HAUNTEDReward.mul(1e12).div(pool.lpSupply)); } return user.amount.mul(accHAUNTEDPerShare).div(1e12).sub(user.rewardDebt); }
7,130,783
./partial_match/1/0x67f354aBf33783b4bf09154aA92F7a96774fC005/sources/contracts/loans/direct/loanTypes/DirectLoanBase.sol
This function is called by a anyone to repay a loan. It can be called at any time after the loan has begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. The the borrower (current owner of the obligation note) will get the collaterl NFT back. This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the contract and hold hostage the NFT's that are still within it. _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator./ Fetch loan details from storage, but store them in memory for the sake of saving gas. Transfer principal-plus-interest-minus-fees from the caller to lender PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the adminFee is low Transfer revenue share from the caller to permitted partner
function _payBackLoan( uint256 _loanId, address _borrower, address _lender, LoanTerms memory _loan ) internal { LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId]; (uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan); IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount); uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare( adminFee, loanExtras.revenueShareInBasisPoints ); if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) { adminFee -= revenueShare; IERC20(_loan.loanERC20Denomination).safeTransferFrom( msg.sender, loanExtras.revenueSharePartner, revenueShare ); } _loanId, _borrower, _lender, _loan.loanPrincipalAmount, _loan.nftCollateralId, payoffAmount, adminFee, revenueShare, _loan.nftCollateralContract, _loan.loanERC20Denomination ); }
2,844,846
./full_match/1/0xa6d6FAaf4dad96478910B83B8eeb5CEdA77F1Dd7/sources/contracts/PresaleV2.sol
100% of bought tokens for 0.08$ Initial amount of usdt user send to buy Parapad 100% of bought tokens for 0.027$ Update mapping to identify where to fetch info about user lock
function claimVested() external { Lock memory userLock; if(islockedOnV2[msg.sender]){ userLock = locks[msg.sender]; ( uint256 total, uint256 max, uint256 paid, uint256 debt,uint256 startTime) = presaleV1.locks(msg.sender); userLock.total = total; userLock.paid = paid; userLock.startTime = forteenNovemberTimestamp; userLock.debt = debt; userLock.max = max; uint256 initialTotal = userLock.total + (userLock.total * 10 / 100); uint256 buyAmount = initialTotal * (usdtDecimals * exchangeRateV1)/(exchangeRatePrecisionV1 * paradoxDecimals); uint256 newTotal = (buyAmount * exchangeRatePrecisionV2 * paradoxDecimals) / (usdtDecimals * exchangeRateV2); userLock.total = newTotal - ((newTotal*10)/100); } uint256 monthsPassed = (block.timestamp - userLock.startTime) / 4 weeks; uint256 release; for (uint256 i = 0; i < monthsPassed; i++) { if (release >= userLock.total) { release = userLock.total; break; } release += monthlyRelease; } uint256 reward = release - userLock.debt; userLock.debt += reward; if(!islockedOnV2[msg.sender]){ islockedOnV2[msg.sender] = true; } para.safeTransfer(msg.sender, reward); }
3,152,832
./partial_match/1/0xDcC7d86dC400838A2380C5A9d5A79106AC9E17a8/sources/FinalToken.sol
destroy the contract and reclaim the leftover funds.
function kill() onlyOwner public returns (bool killed){ selfdestruct(msg.sender); return true; }
4,055,543
./partial_match/4/0x6e68F21aDE819C06beb096ea5059332818F214FC/sources/YFOSIphone12Components.sol
Private function to remove a token from this extension's token tracking data structures. This has O(1) time complexity, but alters the order of the _allTokens array. tokenId uint256 ID of the token to be removed from the tokens list/ To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and then delete the last slot (swap and pop). When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding an 'if' statement (like in _removeTokenFromOwnerEnumeration) This also deletes the contents at the last position of the array _allTokens.length--;
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokensIndex[tokenId] = 0; }
8,705,971
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** * @title cBallot * @dev Implements voting process along with vote delegation */ contract cBallot { struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to uint vote; // index of the voted proposal } struct Proposal { // If you can limit the length to a certain number of bytes, // always use one of bytes1 to bytes32 because they are much cheaper string name; // short name string content; // content of proposal uint voteCount; // number of accumulated votes } uint public nbProposals = 0; address public chairperson; string public proposalsName; mapping(address => Voter) public voters; Proposal[] public proposals; /** * @dev Create a new ballot to choose one of 'proposalNames'. * @param _proposalsName names of proposals */ constructor(string memory _proposalsName) { chairperson = msg.sender; voters[chairperson].weight = 1; proposalsName = _proposalsName; } modifier onlyChairperson { require(msg.sender == chairperson, "Only chairperson can apply"); _; } modifier onlyVoters { require (voters[msg.sender].weight > 0, "only voters can apply"); _; } /** * @dev transfer chairperson Role - transfer ownability * @param _newChairAddress address of new Chairpersonn */ function transferChairpersonRole(address _newChairAddress) external onlyChairperson { chairperson = _newChairAddress; if (voters[_newChairAddress].weight < 1) { voters[_newChairAddress].weight = 1; } } /** * @dev return proposals counter */ function getNbProposals() public view returns(uint) { return nbProposals; } /** * @dev return proposal data * @param _idProposal id of proposal */ function readProposal(uint _idProposal) public view returns( string memory proposalName, string memory proposalContent, uint nbVotes ) { require(_idProposal < nbProposals, "Proposal not found"); return( proposals[_idProposal].name, proposals[_idProposal].content, proposals[_idProposal].voteCount ); } /** * @dev create New Proposal requiring voter role * @param _newProposalName new proposal title * @param _newProposalContent new proposal content */ function addProposal(string memory _newProposalName, string memory _newProposalContent) external onlyVoters { proposals[nbProposals] = Proposal( _newProposalName, _newProposalContent, 0 ); nbProposals++; } /** * @dev Give 'voter' the right to vote on this ballot. May only be called by 'chairperson'. * @param voter address of voter */ function giveRightToVote(address voter) public { require( msg.sender == chairperson, "Only chairperson can give right to vote." ); require( !voters[voter].voted, "The voter already voted." ); require(voters[voter].weight == 0); voters[voter].weight = 1; } /** * @dev Delegate your vote to the voter 'to'. * @param to address to which vote is delegated */ function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; // We found a loop in the delegation, not allowed. require(to != msg.sender, "Found loop in delegation."); } sender.voted = true; sender.delegate = to; Voter storage delegate_ = voters[to]; if (delegate_.voted) { // If the delegate already voted, // directly add to the number of votes proposals[delegate_.vote].voteCount += sender.weight; } else { // If the delegate did not vote yet, // add to her weight. delegate_.weight += sender.weight; } } /** * @dev Give your vote (including votes delegated to you) to proposal 'proposals[proposal].name'. * @param proposal index of proposal in the proposals array */ function vote(uint proposal) public { Voter storage sender = voters[msg.sender]; require(sender.weight != 0, "Has no right to vote"); require(!sender.voted, "Already voted."); sender.voted = true; sender.vote = proposal; // If 'proposal' is out of the range of the array, // this will throw automatically and revert all // changes. proposals[proposal].voteCount += sender.weight; } /** * @dev Computes the winning proposal taking all previous votes into account. * @return winningProposal_ index of winning proposal in the proposals array */ function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } } /** * @dev Calls winningProposal() function to get the index of the winner contained in the proposals array and then * @return winnerName_ the name of the winner */ function winnerName() public view returns (string memory winnerName_) { return proposals[winningProposal()].name; } /** * @dev return winning proposal */ function readWinnerProposal() public view returns( string memory _winnerName, string memory _winnerContent, uint _winnerVoteCount) { return( proposals[winningProposal()].name, proposals[winningProposal()].content, proposals[winningProposal()].voteCount); } }
Computes the winning proposal taking all previous votes into account. return winningProposal_ index of winning proposal in the proposals array/
function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } }
5,479,722
pragma solidity ^0.4.23; library StringUtils { function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); string memory abc; uint k = 0; uint i; bytes memory babc; if (_ba.length==0) { abc = new string(_bc.length); babc = bytes(abc); } else { abc = new string(_ba.length + _bb.length+ _bc.length); babc = bytes(abc); for (i = 0; i < _ba.length; i++) babc[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babc[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) babc[k++] = _bc[i]; return string(babc); } } contract Owned { address public owner; address private candidate; event OwnerChanged(address indexed previousOwner, address indexed newOwner); function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address newOwner) public onlyOwner { require(newOwner != address(0), "Invalid address"); candidate = newOwner; } function confirmOrnerChanging() public { require(candidate == msg.sender, "Only owner candidate can confirm owner changing"); emit OwnerChanged(owner, candidate); owner = candidate; } } contract TestOperations is Owned { uint public minFee = 1 finney; struct Test { uint startTime; uint finishTime; address owner; string scenario; uint reward; // reward for one tester; address[] testers; TestStatus status; bool isRewardPaid; } enum TestStatus { NONE, //0 - test not created WAITING, //1 - waiting for testers READY, //2 - test ready to run RUNNING, //3 - test running FINISHED //4 - test finished } enum TesterState { NONE, //0 - tester not attached to test ATTACHED, //1 - tester attached to test READY, //2 - tester ready to run test FINISHED //3 - tester finished test } struct TestResult { string row; } Test[] internal _tests; mapping(uint => mapping(address => TesterState)) internal _testerStates; // testId => testerAdress => TesterState mapping(uint => string[]) internal _testsResults; // testId => TestResult function createOrder(uint _startTime, address[] _testers, string _scenario) payable public { require(msg.value >= minFee, "Customer is greedy"); require(_testers.length > 0, "Too few testers"); require(_testers.length < 10, "Too many testers"); require(_startTime > now + 5 * 60, "It is impossible to create test in the past"); Test memory _test; _test.startTime = _startTime; _test.owner = msg.sender; _test.scenario = _scenario; _test.testers = _testers; _test.reward = msg.value / _testers.length; //reward for one tester _test.isRewardPaid = false; _test.status = TestStatus.WAITING; uint256 newTestId = _tests.push(_test) - 1; for(uint i = 0; i < _testers.length; i++) { _testerStates[newTestId][_testers[i]] = TesterState.ATTACHED; } emit TestCreated(newTestId, _tests[newTestId].reward); } function payReward(uint testId) testExist(testId) testAtStatus(testId, TestStatus.FINISHED) internal { require(!_tests[testId].isRewardPaid, "Reward already paid"); _tests[testId].isRewardPaid = true; for(uint i = 0; i < _tests[testId].testers.length; i++) { _tests[testId].testers[i].transfer( _tests[testId].reward); } } function getTest(uint testId) public view testExist(testId) returns (uint startTime, uint finishTime, string scenario, uint reward, bool isRewardPaid, TestStatus status, bool amITester) { Test storage test = _tests[testId]; startTime = test.startTime; finishTime = test.finishTime; scenario = test.scenario; reward = test.reward; isRewardPaid = test.isRewardPaid; status = test.status; amITester = _testerStates[testId][msg.sender] != TesterState.NONE; } function getMyTests() public view returns (string tests) { for(uint i = 0; i < _tests.length; i++) { if(_tests[i].owner == msg.sender) { tests = StringUtils.strConcat(tests, ",", StringUtils.uint2str(i)); } } return tests; } //TODO oprimize //Test state calculation depending on tester's states function calculateTestNewState(uint testId) internal returns (TestStatus status) { Test storage _test = _tests[testId]; uint testersCount = _test.testers.length; uint attachedCount; uint readyCount; uint finishedCount; for(uint i = 0; i < testersCount; i++) { TesterState _testerState = _testerStates[testId][_test.testers[i]]; if(_testerState == TesterState.ATTACHED) { attachedCount++; } else if(_testerState == TesterState.READY) { readyCount++; } else if(_testerState == TesterState.FINISHED) { finishedCount++; } } if(readyCount == testersCount && _test.status != TestStatus.RUNNING) { if(_testsResults[testId].length > 0 && _test.status == TestStatus.READY) { status = TestStatus.RUNNING; } else { status = TestStatus.READY; } } else if(finishedCount == testersCount){ status = TestStatus.FINISHED; } else { status = _test.status; } if(status != _tests[testId].status) { _tests[testId].status = status; if(status == TestStatus.FINISHED) { _tests[testId].finishTime = now; } emit TestStatusChanged(testId, status); } } //Modifiers modifier onlyTestOwner(uint testId) { require(_tests[testId].owner == msg.sender, "You are not a test owner!"); _; } modifier onlyTester(uint testId) { require(_testerStates[testId][msg.sender] != TesterState.NONE, "You are not a tester in this test"); _; } modifier testExist(uint testId) { require(testId >= 0 && testId < _tests.length, "Test does not exist"); _; } modifier testerAtState(uint testId, TesterState state) { require(_testerStates[testId][msg.sender] == state, "Invalid tester state"); _; } modifier testAtStatus(uint testId, TestStatus status) { require(_tests[testId].status == status ,"Invalid status of the test"); _; } // System Events // Fired when new test created event TestCreated( uint _id, uint _reward ); // Fired when test status changed event TestStatusChanged( uint _id, TestStatus status ); // Fired when tester state changed for specific test event TesterSateChanged( uint _id, TesterState state ); } contract TesterOperations is TestOperations { function getTestsForTest() public view returns (string tests) { for(uint i = 0; i < _tests.length; i++) { if(_testerStates[i][msg.sender] != TesterState.NONE) { tests = StringUtils.strConcat(tests, ",", StringUtils.uint2str(i)); } } return tests; } //Tester should call this method before test starts function announceReadiness(uint testId, bool isReady) public testExist(testId) onlyTester(testId) testAtStatus(testId, TestStatus.WAITING) returns (TestStatus status) { _testerStates[testId][msg.sender] = isReady ? TesterState.READY : TesterState.ATTACHED; emit TesterSateChanged(testId, _testerStates[testId][msg.sender]); status = calculateTestNewState(testId); } function pushTestResult(uint testId, string result) public testExist(testId) onlyTester(testId) testerAtState(testId, TesterState.READY) returns (TestStatus status) { //require(_tests[testId].startTime <= now, "Test don't start yet"); require(_tests[testId].status == TestStatus.READY || _tests[testId].status == TestStatus.RUNNING, "Test in invalid status"); _testsResults[testId].push(result); status = calculateTestNewState(testId); } //Tester should call this method when he finished test //check that exactly this tester had published some test result before call this method function finishTest(uint testId) public testExist(testId) onlyTester(testId) testerAtState(testId, TesterState.READY) testAtStatus(testId, TestStatus.RUNNING) returns (TestStatus status) { require(_testsResults[testId].length > 0, "It is impossible to finish test before the results are in"); _testerStates[testId][msg.sender] = TesterState.FINISHED; emit TesterSateChanged(testId, TesterState.FINISHED); status = calculateTestNewState(testId); } function getReward(uint testId) public onlyTester(testId) { require(_tests[testId].finishTime > now + 7 * 24 * 60 * 60, "Tester can get reward by his own, if test finished 7 days ago"); payReward(testId); } } contract CustomerOperations is TesterOperations { function getTesterStates(uint testId) public view onlyTestOwner(testId) testExist(testId) returns (string testers) { Test memory test = _tests[testId]; for(uint i = 0; i < test.testers.length; i++) { testers = StringUtils.strConcat(testers, ",", StringUtils.uint2str(i)); testers = StringUtils.strConcat(testers, ":", StringUtils.uint2str(uint(_testerStates[testId][test.testers[i]]))); } } function getTestResults(uint testId) public view onlyTestOwner(testId) testExist(testId) returns (string results){ string[] memory testResults = _testsResults[testId]; for(uint i = 0; i < testResults.length; i++) { results = StringUtils.strConcat(results, ",", testResults[i]); } } function rewardTesters(uint testId) public onlyTestOwner(testId) { payReward(testId); } }
TODO oprimizeTest state calculation depending on tester's states
function calculateTestNewState(uint testId) internal returns (TestStatus status) { Test storage _test = _tests[testId]; uint testersCount = _test.testers.length; uint attachedCount; uint readyCount; uint finishedCount; for(uint i = 0; i < testersCount; i++) { TesterState _testerState = _testerStates[testId][_test.testers[i]]; if(_testerState == TesterState.ATTACHED) { attachedCount++; readyCount++; finishedCount++; } } if(readyCount == testersCount && _test.status != TestStatus.RUNNING) { if(_testsResults[testId].length > 0 && _test.status == TestStatus.READY) { status = TestStatus.RUNNING; status = TestStatus.READY; } status = TestStatus.FINISHED; status = _test.status; } if(status != _tests[testId].status) { _tests[testId].status = status; if(status == TestStatus.FINISHED) { _tests[testId].finishTime = now; } emit TestStatusChanged(testId, status); } }
5,349,509
./full_match/1/0x2d92d57FBef4e333e0FB8629266fC761b5f156cd/sources/browser/JasmyDepositSwapper.sol
require(_fromAmount > 0, "ERR_ZERO_PAYMENT"); will be checked in calcSwap
function swap(uint256 _fromAmount, uint256 _expectedToTokensAmount, uint16 _slippage) private returns (uint256 fromFeeAdd_) { require(_expectedToTokensAmount > 0, "ERR_ZERO_EXPECTED_AMOUNT"); require(_slippage <= 500, "ERR_SLIPPAGE_TOO_BIG"); (uint256 actualToTokensAmount, uint256 fromFeeAdd, uint256 actualFromAmount) = calcSwap(_fromAmount, _isFromEth, _isToToken3); require(actualToTokensAmount > 0, "ERR_ZERO_ACTUAL_TOKENS"); require(_fromAmount == actualFromAmount, "ERR_WRONG_PAYMENT_AMOUNT"); require((actualToTokensAmount >= _expectedToTokensAmount) || (uint256(1000).mul(_expectedToTokensAmount.sub(actualToTokensAmount)) <= _expectedToTokensAmount.mul(_slippage)), "ERR_SLIPPAGE"); if(_isToToken3) { depositToken3Reserve = depositToken3Reserve.sub(actualToTokensAmount); depositToken3.transfer(msg.sender, actualToTokensAmount); } else { depositToken6Reserve = depositToken6Reserve.sub(actualToTokensAmount); depositToken6.transfer(msg.sender, actualToTokensAmount); } fromFeeAdd_ = fromFeeAdd; emit Swap(_fromAmount, _isFromEth, _isToToken3, _expectedToTokensAmount, _slippage, fromFeeAdd_, actualToTokensAmount); }
8,301,082
pragma solidity 0.5.17; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/CEther.sol"; import "../Utils.sol"; contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CUSDC; // The Compound USDC market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInUSDC; uint256 public loanAmountInUSDC; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output USDC after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing bool internal initialized; constructor() public {} function init( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { require(!initialized); initialized = true; // Initialize details of order require(_compoundTokenAddr != _cUSDCAddr); require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs stake = _stake; collateralAmountInUSDC = _collateralAmountInUSDC; loanAmountInUSDC = _loanAmountInUSDC; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CUSDC = CERC20(_cUSDCAddr); CETH_ADDR = _cETHAddr; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); // transfer ownership to msg.sender _transferOwnership(msg.sender); } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public; /** * @notice Sells the Compound order and returns assets to PeakDeFiFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount); /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInUSDC the amount to repay, in USDC */ function repayLoan(uint256 _repayAmountInUSDC) public; /** * @notice Emergency method, which allow to transfer selected tokens to the fund address * @param _tokenAddr address of withdrawn token * @param _receiver address who should receive tokens */ function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner { ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransfer(_receiver, token.balanceOf(address(this))); } function getMarketCollateralFactor() public view returns (uint256); function getCurrentCollateralInUSDC() public returns (uint256 _amount); function getCurrentBorrowInUSDC() public returns (uint256 _amount); function getCurrentCashInUSDC() public view returns (uint256 _amount); /** * @notice Calculates the current profit in USDC * @return the profit amount */ function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 l; uint256 r; if (isSold) { l = outputAmount; r = collateralAmountInUSDC; } else { uint256 cash = getCurrentCashInUSDC(); uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (cash >= borrow) { l = supply.add(cash); r = borrow.add(collateralAmountInUSDC); } else { l = supply; r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC); } } if (l >= r) { return (false, l.sub(r)); } else { return (true, r.sub(l)); } } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (borrow == 0) { return uint256(-1); } return supply.mul(PRECISION).div(borrow); } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor()); if (supply >= borrow) { return (false, supply.sub(borrow)); } else { return (true, borrow.sub(supply)); } } function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } // Convert a USDC amount to the amount of a given token that's of equal value function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) { ERC20Detailed t = __underlyingToken(_cToken); return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION)); } // Convert a compound token amount to the amount of USDC that's of equal value function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) { return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION); } function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) { if (_cToken == CETH_ADDR) { // ETH return ETH_TOKEN_ADDRESS; } CERC20 ct = CERC20(_cToken); address underlyingToken = ct.underlying(); ERC20Detailed t = ERC20Detailed(underlyingToken); return t; } function() external payable {} } pragma solidity ^0.5.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.17; // Compound finance comptroller interface Comptroller { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } pragma solidity 0.5.17; // Compound finance's price oracle interface PriceOracle { // returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision) function getUnderlyingPrice(address cToken) external view returns (uint); } pragma solidity 0.5.17; // Compound finance ERC20 market interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } pragma solidity 0.5.17; // Compound finance Ether market interface interface CEther { function mint() external payable; function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow() external payable; function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/KyberNetwork.sol"; import "./interfaces/OneInchExchange.sol"; /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public USDC_ADDR; address payable public KYBER_ADDR; address payable public ONEINCH_ADDR; bytes public constant PERM_HINT = "PERM"; // The address Kyber Network uses to represent Ether ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal usdc; KyberNetwork internal kyber; uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_DECIMALS = 18; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr ) public { USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, 1, address(0), PERM_HINT ); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Wrapper function for doing token conversion on 1inch * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 beforeDestBalance = getBalance(_destToken, address(this)); // Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error if (_srcToken != ETH_TOKEN_ADDRESS) { _actualSrcAmount = 0; OneInchExchange dex = OneInchExchange(ONEINCH_ADDR); address approvalHandler = dex.spender(); _srcToken.safeApprove(approvalHandler, 0); _srcToken.safeApprove(approvalHandler, _srcAmount); } else { _actualSrcAmount = _srcAmount; } // trade through 1inch proxy (bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata); require(success); // calculate trade amounts and price _actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) internal view returns(bool) { uint256 size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface KyberNetwork { function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } pragma solidity 0.5.17; interface OneInchExchange { function spender() external view returns (address); } pragma solidity 0.5.17; import "./LongCERC20Order.sol"; import "./LongCEtherOrder.sol"; import "./ShortCERC20Order.sol"; import "./ShortCEtherOrder.sol"; import "../lib/CloneFactory.sol"; contract CompoundOrderFactory is CloneFactory { address public SHORT_CERC20_LOGIC_CONTRACT; address public SHORT_CEther_LOGIC_CONTRACT; address public LONG_CERC20_LOGIC_CONTRACT; address public LONG_CEther_LOGIC_CONTRACT; address public USDC_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CUSDC_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CUSDC_ADDR = _cUSDCAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType ) external returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address payable clone; if (_compoundTokenAddr != CETH_ADDR) { if (_orderType) { // Short CERC20 Order clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT)); } else { // Long CERC20 Order clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT)); } } else { if (_orderType) { // Short CEther Order clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT)); } else { // Long CEther Order clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT)); } } order = CompoundOrder(clone); order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType, USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } function tokenIsListed(address _compoundTokenAddr) external view returns (bool) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (bool isListed,) = troll.markets(_compoundTokenAddr); return isListed; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CERC20 market = CERC20(compoundTokenAddr); ERC20Detailed token = __underlyingToken(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(token.balanceOf(address(this))); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); uint256 leftoverTokens = token.balanceOf(address(this)); if (leftoverTokens > 0) { token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens } } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CEther market = CEther(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(address(this).balance); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications ERC20Detailed token = __underlyingToken(compoundTokenAddr); if (token.balanceOf(address(this)) > 0) { uint256 repayAmount = token.balanceOf(address(this)); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, repayAmount); require(market.repayBorrow(repayAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CERC20 market = CERC20(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, actualTokenAmount); require(market.repayBorrow(actualTokenAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications if (address(this).balance > 0) { uint256 repayAmount = address(this).balance; market.repayBorrow.value(repayAmount)(); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CEther market = CEther(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound market.repayBorrow.value(actualTokenAmount)(); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } pragma solidity 0.5.17; interface IMiniMeToken { function balanceOf(address _owner) external view returns (uint256 balance); function totalSupply() external view returns(uint); function generateTokens(address _owner, uint _amount) external returns (bool); function destroyTokens(address _owner, uint _amount) external returns (bool); function totalSupplyAt(uint _blockNumber) external view returns(uint); function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint); function transferOwnership(address newOwner) external; } pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; function __initReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.17; // interface for contract_v6/UniswapOracle.sol interface IUniswapOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {} } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "../../access/roles/MinterRole.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/roles/SignerRole.sol"; import "../staking/PeakStaking.sol"; import "../PeakToken.sol"; import "../IUniswapOracle.sol"; contract PeakReward is SignerRole { using SafeMath for uint256; using SafeERC20 for IERC20; event Register(address user, address referrer); event RankChange(address user, uint256 oldRank, uint256 newRank); event PayCommission( address referrer, address recipient, address token, uint256 amount, uint8 level ); event ChangedCareerValue(address user, uint256 changeAmount, bool positive); event ReceiveRankReward(address user, uint256 peakReward); modifier regUser(address user) { if (!isUser[user]) { isUser[user] = true; emit Register(user, address(0)); } _; } uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant USDC_PRECISION = 10**6; uint8 internal constant COMMISSION_LEVELS = 8; mapping(address => address) public referrerOf; mapping(address => bool) public isUser; mapping(address => uint256) public careerValue; // AKA DSV mapping(address => uint256) public rankOf; mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank uint256[] public commissionPercentages; uint256[] public commissionStakeRequirements; uint256 public mintedPeakTokens; address public marketPeakWallet; PeakStaking public peakStaking; PeakToken public peakToken; address public stablecoin; IUniswapOracle public oracle; constructor( address _marketPeakWallet, address _peakStaking, address _peakToken, address _stablecoin, address _oracle ) public { // initialize commission percentages for each level commissionPercentages.push(10 * (10**16)); // 10% commissionPercentages.push(4 * (10**16)); // 4% commissionPercentages.push(2 * (10**16)); // 2% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(5 * (10**15)); // 0.5% commissionPercentages.push(5 * (10**15)); // 0.5% // initialize commission stake requirements for each level commissionStakeRequirements.push(0); commissionStakeRequirements.push(PEAK_PRECISION.mul(2000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(4000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(6000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(7000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(8000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(9000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(10000)); // initialize rank rewards for (uint256 i = 0; i < 8; i = i.add(1)) { uint256 rewardInUSDC = 0; for (uint256 j = i.add(1); j <= 8; j = j.add(1)) { if (j == 1) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100)); } else if (j == 2) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300)); } else if (j == 3) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600)); } else if (j == 4) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200)); } else if (j == 5) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400)); } else if (j == 6) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500)); } else if (j == 7) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000)); } else { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000)); } rankReward[i][j] = rewardInUSDC; } } marketPeakWallet = _marketPeakWallet; peakStaking = PeakStaking(_peakStaking); peakToken = PeakToken(_peakToken); stablecoin = _stablecoin; oracle = IUniswapOracle(_oracle); } /** @notice Registers a group of referrals relationship. @param users The array of users @param referrers The group of referrers of `users` */ function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner { require(users.length == referrers.length, "PeakReward: arrays length are not equal"); for (uint256 i = 0; i < users.length; i++) { refer(users[i], referrers[i]); } } /** @notice Registers a referral relationship @param user The user who is being referred @param referrer The referrer of `user` */ function refer(address user, address referrer) public onlySigner { require(!isUser[user], "PeakReward: referred is already a user"); require(user != referrer, "PeakReward: can't refer self"); require( user != address(0) && referrer != address(0), "PeakReward: 0 address" ); isUser[user] = true; isUser[referrer] = true; referrerOf[user] = referrer; downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1); emit Register(user, referrer); } function canRefer(address user, address referrer) public view returns (bool) { return !isUser[user] && user != referrer && user != address(0) && referrer != address(0); } /** @notice Distributes commissions to a referrer and their referrers @param referrer The referrer who will receive commission @param commissionToken The ERC20 token that the commission is paid in @param rawCommission The raw commission that will be distributed amongst referrers @param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak. */ function payCommission( address referrer, address commissionToken, uint256 rawCommission, bool returnLeftovers ) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) { // transfer the raw commission from `msg.sender` IERC20 token = IERC20(commissionToken); token.safeTransferFrom(msg.sender, address(this), rawCommission); // payout commissions to referrers of different levels address ptr = referrer; uint256 commissionLeft = rawCommission; uint8 i = 0; while (ptr != address(0) && i < COMMISSION_LEVELS) { if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) { // referrer has enough stake, give commission uint256 com = rawCommission.mul(commissionPercentages[i]).div( COMMISSION_RATE ); if (com > commissionLeft) { com = commissionLeft; } token.safeTransfer(ptr, com); commissionLeft = commissionLeft.sub(com); if (commissionToken == address(peakToken)) { incrementCareerValueInPeak(ptr, com); } else if (commissionToken == stablecoin) { incrementCareerValueInUsdc(ptr, com); } emit PayCommission(referrer, ptr, commissionToken, com, i); } ptr = referrerOf[ptr]; i += 1; } // handle leftovers if (returnLeftovers) { // return leftovers to `msg.sender` token.safeTransfer(msg.sender, commissionLeft); return commissionLeft; } else { // give leftovers to MarketPeak wallet token.safeTransfer(marketPeakWallet, commissionLeft); return 0; } } /** @notice Increments a user's career value @param user The user @param incCV The CV increase amount, in Usdc */ function incrementCareerValueInUsdc(address user, uint256 incCV) public regUser(user) onlySigner { careerValue[user] = careerValue[user].add(incCV); emit ChangedCareerValue(user, incCV, true); } /** @notice Increments a user's career value @param user The user @param incCVInPeak The CV increase amount, in PEAK tokens */ function incrementCareerValueInPeak(address user, uint256 incCVInPeak) public regUser(user) onlySigner { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div( PEAK_PRECISION ); careerValue[user] = careerValue[user].add(incCVInUsdc); emit ChangedCareerValue(user, incCVInUsdc, true); } /** @notice Returns a user's rank in the PeakDeFi system based only on career value @param user The user whose rank will be queried */ function cvRankOf(address user) public view returns (uint256) { uint256 cv = careerValue[user]; if (cv < USDC_PRECISION.mul(100)) { return 0; } else if (cv < USDC_PRECISION.mul(250)) { return 1; } else if (cv < USDC_PRECISION.mul(750)) { return 2; } else if (cv < USDC_PRECISION.mul(1500)) { return 3; } else if (cv < USDC_PRECISION.mul(3000)) { return 4; } else if (cv < USDC_PRECISION.mul(10000)) { return 5; } else if (cv < USDC_PRECISION.mul(50000)) { return 6; } else if (cv < USDC_PRECISION.mul(150000)) { return 7; } else { return 8; } } function rankUp(address user) external { // verify rank up conditions uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); require(cvRank > currentRank, "PeakReward: career value is not enough!"); require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!"); // Target rank always should be +1 rank from current rank uint256 targetRank = currentRank + 1; // increase user rank rankOf[user] = targetRank; emit RankChange(user, currentRank, targetRank); address referrer = referrerOf[user]; if (referrer != address(0)) { downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank] .add(1); downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank] .sub(1); } // give user rank reward uint256 rewardInPeak = rankReward[currentRank][targetRank] .mul(PEAK_PRECISION) .div(_getPeakPriceInUsdc()); if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) { // mint if under cap, do nothing if over cap mintedPeakTokens = mintedPeakTokens.add(rewardInPeak); peakToken.mint(user, rewardInPeak); emit ReceiveRankReward(user, rewardInPeak); } } function canRankUp(address user) external view returns (bool) { uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); return (cvRank > currentRank) && (downlineRanks[user][currentRank] >= 2 || currentRank == 0); } /** @notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`. @param user The user whose stake will be queried */ function _peakStakeOf(address user) internal view returns (uint256) { return peakStaking.userStakeAmount(user); } /** @notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`. */ function _getPeakPriceInUsdc() internal returns (uint256) { oracle.update(); uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION); if (priceInUSDC == 0) { return USDC_PRECISION.mul(3).div(10); } return priceInUSDC; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract SignerRole is Context { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private _signers; constructor () internal { _addSigner(_msgSender()); } modifier onlySigner() { require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role"); _; } function isSigner(address account) public view returns (bool) { return _signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(_msgSender()); } function _addSigner(address account) internal { _signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { _signers.remove(account); emit SignerRemoved(account); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../reward/PeakReward.sol"; import "../PeakToken.sol"; contract PeakStaking { using SafeMath for uint256; using SafeERC20 for PeakToken; event CreateStake( uint256 idx, address user, address referrer, uint256 stakeAmount, uint256 stakeTimeInDays, uint256 interestAmount ); event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawStake(uint256 idx, address user); uint256 internal constant PRECISION = 10**18; uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak) uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10% uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015 uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6 uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days uint256 internal constant DAY_IN_SECONDS = 86400; uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3% uint256 internal constant YEAR_IN_DAYS = 365; uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK struct Stake { address staker; uint256 stakeAmount; uint256 interestAmount; uint256 withdrawnInterestAmount; uint256 stakeTimestamp; uint256 stakeTimeInDays; bool active; } Stake[] public stakeList; mapping(address => uint256) public userStakeAmount; uint256 public mintedPeakTokens; bool public initialized; PeakToken public peakToken; PeakReward public peakReward; constructor(address _peakToken) public { peakToken = PeakToken(_peakToken); } function init(address _peakReward) public { require(!initialized, "PeakStaking: Already initialized"); initialized = true; peakReward = PeakReward(_peakReward); } function stake( uint256 stakeAmount, uint256 stakeTimeInDays, address referrer ) public returns (uint256 stakeIdx) { require( stakeTimeInDays >= MIN_STAKE_PERIOD, "PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD" ); require( stakeTimeInDays <= MAX_STAKE_PERIOD, "PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD" ); // record stake uint256 interestAmount = getInterestAmount( stakeAmount, stakeTimeInDays ); stakeIdx = stakeList.length; stakeList.push( Stake({ staker: msg.sender, stakeAmount: stakeAmount, interestAmount: interestAmount, withdrawnInterestAmount: 0, stakeTimestamp: now, stakeTimeInDays: stakeTimeInDays, active: true }) ); mintedPeakTokens = mintedPeakTokens.add(interestAmount); userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add( stakeAmount ); // transfer PEAK from msg.sender peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount); // mint PEAK interest peakToken.mint(address(this), interestAmount); // handle referral if (peakReward.canRefer(msg.sender, referrer)) { peakReward.refer(msg.sender, referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { // pay referral bonus to referrer uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div( PRECISION ); peakToken.mint(address(this), rawCommission); peakToken.safeApprove(address(peakReward), rawCommission); uint256 leftoverAmount = peakReward.payCommission( actualReferrer, address(peakToken), rawCommission, true ); peakToken.burn(leftoverAmount); // pay referral bonus to staker uint256 referralStakerBonus = interestAmount .mul(REFERRAL_STAKER_BONUS) .div(PRECISION); peakToken.mint(msg.sender, referralStakerBonus); mintedPeakTokens = mintedPeakTokens.add( rawCommission.sub(leftoverAmount).add(referralStakerBonus) ); emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus); } require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap"); emit CreateStake( stakeIdx, msg.sender, actualReferrer, stakeAmount, stakeTimeInDays, interestAmount ); } function withdraw(uint256 stakeIdx) public { Stake storage stakeObj = stakeList[stakeIdx]; require( stakeObj.staker == msg.sender, "PeakStaking: Sender not staker" ); require(stakeObj.active, "PeakStaking: Not active"); // calculate amount that can be withdrawn uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul( DAY_IN_SECONDS ); uint256 withdrawAmount; if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) { // matured, withdraw all withdrawAmount = stakeObj .stakeAmount .add(stakeObj.interestAmount) .sub(stakeObj.withdrawnInterestAmount); stakeObj.active = false; stakeObj.withdrawnInterestAmount = stakeObj.interestAmount; userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub( stakeObj.stakeAmount ); emit WithdrawReward( stakeIdx, msg.sender, stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount) ); emit WithdrawStake(stakeIdx, msg.sender); } else { // not mature, partial withdraw withdrawAmount = stakeObj .interestAmount .mul(uint256(now).sub(stakeObj.stakeTimestamp)) .div(stakeTimeInSeconds) .sub(stakeObj.withdrawnInterestAmount); // record withdrawal stakeObj.withdrawnInterestAmount = stakeObj .withdrawnInterestAmount .add(withdrawAmount); emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount); } // withdraw interest to sender peakToken.safeTransfer(msg.sender, withdrawAmount); } function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays) public view returns (uint256) { uint256 earlyFactor = _earlyFactor(mintedPeakTokens); uint256 biggerBonus = stakeAmount.mul(PRECISION).div( BIGGER_BONUS_DIVISOR ); if (biggerBonus > MAX_BIGGER_BONUS) { biggerBonus = MAX_BIGGER_BONUS; } // convert yearly bigger bonus to stake time biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS); uint256 longerBonus = _longerBonus(stakeTimeInDays); uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div( PRECISION ); uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION); return interestAmount; } function _longerBonus(uint256 stakeTimeInDays) internal pure returns (uint256) { return DAILY_BASE_REWARD.mul(stakeTimeInDays).add( DAILY_GROWING_REWARD .mul(stakeTimeInDays) .mul(stakeTimeInDays.add(1)) .div(2) ); } function _earlyFactor(uint256 _mintedPeakTokens) internal pure returns (uint256) { uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION); if (tmp > PRECISION) { return 0; } return PRECISION.sub(tmp); } } pragma solidity 0.5.17; import "./lib/CloneFactory.sol"; import "./tokens/minime/MiniMeToken.sol"; import "./PeakDeFiFund.sol"; import "./PeakDeFiProxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract PeakDeFiFactory is CloneFactory { using Address for address; event CreateFund(address fund); event InitFund(address fund, address proxy); address public usdcAddr; address payable public kyberAddr; address payable public oneInchAddr; address payable public peakdefiFund; address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; address public peakRewardAddr; address public peakStakingAddr; MiniMeTokenFactory public minimeFactory; mapping(address => address) public fundCreator; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr, address payable _peakdefiFund, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, address _peakRewardAddr, address _peakStakingAddr, address _minimeFactoryAddr ) public { usdcAddr = _usdcAddr; kyberAddr = _kyberAddr; oneInchAddr = _oneInchAddr; peakdefiFund = _peakdefiFund; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; peakRewardAddr = _peakRewardAddr; peakStakingAddr = _peakStakingAddr; minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr); } function createFund() external returns (PeakDeFiFund) { // create fund PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable()); fund.initOwner(); // give PeakReward signer rights to fund PeakReward peakReward = PeakReward(peakRewardAddr); peakReward.addSigner(address(fund)); fundCreator[address(fund)] = msg.sender; emit CreateFund(address(fund)); return fund; } function initFund1( PeakDeFiFund fund, string calldata reptokenName, string calldata reptokenSymbol, string calldata sharesName, string calldata sharesSymbol ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); // create tokens MiniMeToken reptoken = minimeFactory.createCloneToken( address(0), 0, reptokenName, 18, reptokenSymbol, false ); MiniMeToken shares = minimeFactory.createCloneToken( address(0), 0, sharesName, 18, sharesSymbol, true ); MiniMeToken peakReferralToken = minimeFactory.createCloneToken( address(0), 0, "Peak Referral Token", 18, "PRT", false ); // transfer token ownerships to fund reptoken.transferOwnership(address(fund)); shares.transferOwnership(address(fund)); peakReferralToken.transferOwnership(address(fund)); fund.initInternalTokens( address(reptoken), address(shares), address(peakReferralToken) ); } function initFund2( PeakDeFiFund fund, address payable _devFundingAccount, uint256 _devFundingRate, uint256[2] calldata _phaseLengths, address _compoundFactoryAddr ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initParams( _devFundingAccount, _phaseLengths, _devFundingRate, address(0), usdcAddr, kyberAddr, _compoundFactoryAddr, peakdefiLogic, peakdefiLogic2, peakdefiLogic3, 1, oneInchAddr, peakRewardAddr, peakStakingAddr ); } function initFund3( PeakDeFiFund fund, uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initRegistration( _newManagerRepToken, _maxNewManagersPerCycle, _reptokenPrice, _peakManagerStakeRequired, _isPermissioned ); } function initFund4( PeakDeFiFund fund, address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initTokenListings(_kyberTokens, _compoundTokens); // deploy and set PeakDeFiProxy PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund)); fund.setProxy(address(proxy).toPayable()); // transfer fund ownership to msg.sender fund.transferOwnership(msg.sender); emit InitFund(address(fund), address(proxy)); } } pragma solidity 0.5.17; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./TokenController.sol"; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /// @dev The actual token contract, the default owner is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token owner contract, which Giveth will call a "Campaign" contract MiniMeToken is Ownable { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.2"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address payable _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The owner of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // owner of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != owner()) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token owner of the transfer if (isContract(owner())) { require(TokenController(owner()).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token owner of the approve function call if (isContract(owner())) { require(TokenController(owner()).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string memory _cloneTokenName, uint8 _cloneDecimalUnits, string memory _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( address(this), snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.transferOwnership(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyOwner returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(0), _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(0), _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's owner has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token owner contract function () external payable { require(isContract(owner())); require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) public onlyOwner { if (_token == address(0)) { address(uint160(owner())).transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance)); emit ClaimedTokens(_token, owner(), balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { event CreatedToken(string symbol, address addr); /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the owner of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address payable _parentToken, uint _snapshotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( address(this), _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.transferOwnership(msg.sender); emit CreatedToken(_tokenSymbol, address(newToken)); return newToken; } } pragma solidity 0.5.17; /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title The main smart contract of the PeakDeFi hedge fund. * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiFund is PeakDeFiStorage, Utils(address(0), address(0), address(0)), TokenController { /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require( now > startTimeOfCyclePhase.add( phaseLengths[uint256(CyclePhase.Intermission)] ) ); _; } /** * Meta functions */ function initParams( address payable _devFundingAccount, uint256[2] calldata _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _usdcAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, uint256 _startCycleNumber, address payable _oneInchAddr, address _peakRewardAddr, address _peakStakingAddr ) external { require(proxyAddr == address(0)); devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Intermission; compoundFactoryAddr = _compoundFactoryAddr; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; previousVersion = _previousVersion; cycleNumber = _startCycleNumber; peakReward = PeakReward(_peakRewardAddr); peakStaking = PeakStaking(_peakStakingAddr); USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); __initReentrancyGuard(); } function initOwner() external { require(proxyAddr == address(0)); _transferOwnership(msg.sender); } function initInternalTokens( address payable _repAddr, address payable _sTokenAddr, address payable _peakReferralTokenAddr ) external onlyOwner { require(controlTokenAddr == address(0)); require(_repAddr != address(0)); controlTokenAddr = _repAddr; shareTokenAddr = _sTokenAddr; cToken = IMiniMeToken(_repAddr); sToken = IMiniMeToken(_sTokenAddr); peakReferralToken = IMiniMeToken(_peakReferralTokenAddr); } function initRegistration( uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external onlyOwner { require(_newManagerRepToken > 0 && newManagerRepToken == 0); newManagerRepToken = _newManagerRepToken; maxNewManagersPerCycle = _maxNewManagersPerCycle; reptokenPrice = _reptokenPrice; peakManagerStakeRequired = _peakManagerStakeRequired; isPermissioned = _isPermissioned; } function initTokenListings( address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i++) { isKyberToken[_kyberTokens[i]] = true; } CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr); for (i = 0; i < _compoundTokens.length; i++) { require(factory.tokenIsListed(_compoundTokens[i])); isCompoundToken[_compoundTokens[i]] = true; } } /** * @notice Used during deployment to set the PeakDeFiProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) external onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = PeakDeFiProxyInterface(_proxyAddr); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public returns (bool _success) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.developerInitiateUpgrade.selector, _candidate ) ); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's * address in PeakDeFiProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); peakReferralToken.transferOwnership(nextVersion); proxy.updatePeakDeFiFundAddress(); } /** * @notice Transfers assets to the next version. * @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether. */ function transferAssetToNextVersion(address _assetAddress) public nonReentrant readyForUpgradeMigration isValidToken(_assetAddress) { if (_assetAddress == address(ETH_TOKEN_ADDRESS)) { nextVersion.transfer(address(this).balance); } else { ERC20Detailed token = ERC20Detailed(_assetAddress); token.safeTransfer(nextVersion, token.balanceOf(address(this))); } } /** * Getters */ /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Returns the length of the user's compound orders array. * @return length of the user's compound orders array */ function compoundOrdersCount(address _userAddr) public view returns (uint256 _count) { return userCompoundOrders[_userAddr].length; } /** * @notice Returns the phaseLengths array. * @return the phaseLengths array */ function getPhaseLengths() public view returns (uint256[2] memory _phaseLengths) { return phaseLengths; } /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.commissionOfAt.selector, _manager, _cycle ) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * Parameter setters */ /** * @notice Changes the address to which the developer fees will be sent. Only callable by owner. * @param _newAddr the new developer fee address */ function changeDeveloperFeeAccount(address payable _newAddr) public onlyOwner { require(_newAddr != address(0) && _newAddr != address(this)); devFundingAccount = _newAddr; } /** * @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner. * @param _newProp the new proportion, fixed point decimal */ function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner { require(_newProp < PRECISION); require(_newProp < devFundingRate); devFundingRate = _newProp; } /** * @notice Allows managers to invest in a token. Only callable by owner. * @param _token address of the token to be listed */ function listKyberToken(address _token) public onlyOwner { isKyberToken[_token] = true; } /** * @notice Allows managers to invest in a Compound token. Only callable by owner. * @param _token address of the Compound token to be listed */ function listCompoundToken(address _token) public onlyOwner { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); require(factory.tokenIsListed(_token)); isCompoundToken[_token] = true; } /** * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.nextPhase.selector) ); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithUSDC.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithETH.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.registerWithToken.selector, _token, _donationInTokens ) ); if (!success) { revert(); } } /** * Intermission phase functions */ /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. */ function depositEther(address _referrer) public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.depositEther.selector, _referrer) ); if (!success) { revert(); } } function depositEtherAdvanced( bool _useKyber, bytes calldata _calldata, address _referrer ) external payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositEtherAdvanced.selector, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. */ function depositUSDC(uint256 _usdcAmount, address _referrer) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositUSDC.selector, _usdcAmount, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. */ function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositToken.selector, _tokenAddr, _tokenAmount, _referrer ) ); if (!success) { revert(); } } function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes calldata _calldata, address _referrer ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositTokenAdvanced.selector, _tokenAddr, _tokenAmount, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC) ); if (!success) { revert(); } } function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawEtherAdvanced.selector, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC) ); if (!success) { revert(); } } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawToken.selector, _tokenAddr, _amountInUSDC ) ); if (!success) { revert(); } } function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawTokenAdvanced.selector, _tokenAddr, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.redeemCommission.selector, _inShares) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.redeemCommissionForCycle.selector, _inShares, _cycle ) ); if (!success) { revert(); } } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverToken.selector, _tokenAddr, _calldata ) ); if (!success) { revert(); } } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverCompoundOrder.selector, _orderAddress ) ); if (!success) { revert(); } } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector(this.burnDeadman.selector, _deadman) ); if (!success) { revert(); } } /** * Manage phase functions */ function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, _orderId, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, _orderId, _repayAmountInUSDC, _manager, _salt, _signature ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestment.selector, _tokenAddress, _stake, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentV2.selector, _sender, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAssetV2.selector, _sender, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrder.selector, _sender, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrder.selector, _sender, _orderId, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrder.selector, _sender, _orderId, _repayAmountInUSDC ) ); if (!success) { revert(); } } /** * @notice Emergency exit the tokens from order contract during intermission stage * @param _sender the address of trader, who created the order * @param _orderId the ID of the Compound order * @param _tokenAddr the address of token which should be transferred * @param _receiver the address of receiver */ function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public onlyOwner { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.emergencyExitCompoundTokens.selector, _sender, _orderId, _tokenAddr, _receiver ) ); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @return True if the ether is accepted, false if it throws */ function proxyPayment( address /*_owner*/ ) public payable returns (bool) { return false; } /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @return False if the controller does not authorize the transfer */ function onTransfer( address, /*_from*/ address, /*_to*/ uint256 /*_amount*/ ) public returns (bool) { return true; } /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @return False if the controller does not authorize the approval */ function onApprove( address, /*_owner*/ address, /*_spender*/ uint256 /*_amount*/ ) public returns (bool) { return true; } function() external payable {} /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance and the received penalty, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionBalanceOf.selector, _referrer ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionOfAt.selector, _referrer, _cycle ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.peakReferralRedeemCommission.selector) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralRedeemCommissionForCycle.selector, _cycle ) ); if (!success) { revert(); } } /** * @notice Changes the required PEAK stake of a new manager. Only callable by owner. * @param _newValue the new value */ function peakChangeManagerStakeRequired(uint256 _newValue) public onlyOwner { peakManagerStakeRequired = _newValue; } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./lib/ReentrancyGuard.sol"; import "./interfaces/IMiniMeToken.sol"; import "./tokens/minime/TokenController.sol"; import "./Utils.sol"; import "./PeakDeFiProxyInterface.sol"; import "./peak/reward/PeakReward.sol"; import "./peak/staking/PeakStaking.sol"; /** * @title The storage layout of PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiStorage is Ownable, ReentrancyGuard { using SafeMath for uint256; enum CyclePhase {Intermission, Manage} enum VoteDirection {Empty, For, Against} enum Subchunk {Propose, Vote} struct Investment { address tokenAddress; uint256 cycleNumber; uint256 stake; uint256 tokenAmount; uint256 buyPrice; // token buy price in 18 decimals in USDC uint256 sellPrice; // token sell price in 18 decimals in USDC uint256 buyTime; uint256 buyCostInUSDC; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase(). uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5) uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5) uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle. // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Checks if the fund has been initialized bool public isInitialized; // Address of the RepToken token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the PeakDeFiProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the PeakDeFiLogic contract. address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of PeakDeFiFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInUSDC; // The total funds at the beginning of the current management phase uint256 public totalFundsAtManagePhaseStart; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal. uint256 public devFundingRate; // Total amount of commission unclaimed by managers uint256 public totalCommissionLeft; // Stores the lengths of each cycle phase in seconds. uint256[2] public phaseLengths; // The number of managers onboarded during the current cycle uint256 public managersOnboardedThisCycle; // The amount of RepToken tokens a new manager receves uint256 public newManagerRepToken; // The max number of new managers that can be onboarded in one cycle uint256 public maxNewManagersPerCycle; // The price of RepToken in USDC uint256 public reptokenPrice; // The last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) internal _lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) internal _hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) internal _baseRiskStakeFallback; // List of investments of a manager in the current cycle. mapping(address => Investment[]) public userInvestments; // List of short/long orders of a manager in the current cycle. mapping(address => address payable[]) public userCompoundOrders; // Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission) mapping(uint256 => uint256) internal _totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) internal _managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) internal _lastActiveCycle; // Checks if an address points to a whitelisted Kyber token. mapping(address => bool) public isKyberToken; // Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // The current cycle phase. CyclePhase public cyclePhase; // Upgrade governance related variables bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized address payable public nextVersion; // Address of the next version of PeakDeFiFund. // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; PeakDeFiProxyInterface internal proxy; // PeakDeFi uint256 public peakReferralTotalCommissionLeft; uint256 public peakManagerStakeRequired; mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle; mapping(address => uint256) internal _peakReferralLastCommissionRedemption; mapping(address => mapping(uint256 => bool)) internal _peakReferralHasRedeemedCommissionForCycle; IMiniMeToken public peakReferralToken; PeakReward public peakReward; PeakStaking public peakStaking; bool public isPermissioned; mapping(address => mapping(uint256 => bool)) public hasUsedSalt; // Events event ChangedPhase( uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInUSDC ); event Deposit( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event Withdraw( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event CreatedInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costUSDCAmount, uint256 _tokenAmount ); event SoldInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedRepToken, uint256 _sellPrice, uint256 _earnedUSDCAmount ); event CreatedCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costUSDCAmount ); event SoldCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedRepToken, uint256 _earnedUSDCAmount ); event RepaidCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidUSDCAmount ); event CommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event TotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); event Register( address indexed _manager, uint256 _donationInUSDC, uint256 _reptokenReceived ); event BurnDeadman(address indexed _manager, uint256 _reptokenBurned); event DeveloperInitiatedUpgrade( uint256 indexed _cycleNumber, address _candidate ); event FinalizedNextVersion( uint256 indexed _cycleNumber, address _nextVersion ); event PeakReferralCommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event PeakReferralTotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); /* Helper functions shared by both PeakDeFiLogic & PeakDeFiFund */ function lastCommissionRedemption(address _manager) public view returns (uint256) { if (_lastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastCommissionRedemption( _manager ); } return _lastCommissionRedemption[_manager]; } function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle) public view returns (bool) { if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .hasRedeemedCommissionForCycle(_manager, _cycle); } return _hasRedeemedCommissionForCycle[_manager][_cycle]; } function riskTakenInCycle(address _manager, uint256 _cycle) public view returns (uint256) { if (_riskTakenInCycle[_manager][_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).riskTakenInCycle( _manager, _cycle ); } return _riskTakenInCycle[_manager][_cycle]; } function baseRiskStakeFallback(address _manager) public view returns (uint256) { if (_baseRiskStakeFallback[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).baseRiskStakeFallback( _manager ); } return _baseRiskStakeFallback[_manager]; } function totalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_totalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionOfCycle( _cycle ); } return _totalCommissionOfCycle[_cycle]; } function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) { if (_managePhaseEndBlock[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).managePhaseEndBlock( _cycle ); } return _managePhaseEndBlock[_cycle]; } function lastActiveCycle(address _manager) public view returns (uint256) { if (_lastActiveCycle[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastActiveCycle(_manager); } return _lastActiveCycle[_manager]; } /** PeakDeFi */ function peakReferralLastCommissionRedemption(address _manager) public view returns (uint256) { if (_peakReferralLastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralLastCommissionRedemption(_manager); } return _peakReferralLastCommissionRedemption[_manager]; } function peakReferralHasRedeemedCommissionForCycle( address _manager, uint256 _cycle ) public view returns (bool) { if ( _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] == false ) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .peakReferralHasRedeemedCommissionForCycle( _manager, _cycle ); } return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle]; } function peakReferralTotalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralTotalCommissionOfCycle(_cycle); } return _peakReferralTotalCommissionOfCycle[_cycle]; } } pragma solidity 0.5.17; interface PeakDeFiProxyInterface { function peakdefiFundAddress() external view returns (address payable); function updatePeakDeFiFundAddress() external; } pragma solidity 0.5.17; import "./PeakDeFiFund.sol"; contract PeakDeFiProxy { address payable public peakdefiFundAddress; event UpdatedFundAddress(address payable _newFundAddr); constructor(address payable _fundAddr) public { peakdefiFundAddress = _fundAddr; emit UpdatedFundAddress(_fundAddr); } function updatePeakDeFiFundAddress() public { require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund"); address payable nextVersion = PeakDeFiFund(peakdefiFundAddress) .nextVersion(); require(nextVersion != address(0), "Next version can't be empty"); peakdefiFundAddress = nextVersion; emit UpdatedFundAddress(peakdefiFundAddress); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require( cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD ); uint256 balance = cToken.balanceOf(_deadman); require(cToken.destroyTokens(_deadman, balance)); emit BurnDeadman(_deadman, balance); } /** * @notice Creates a new investment for an ERC20 token. Backwards compatible. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { bytes memory nil; createInvestmentV2( msg.sender, _tokenAddress, _stake, _maxPrice, nil, true ); } function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, abi.encode( _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createInvestmentV2( _manager, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. Backwards compatible. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { bytes memory nil; sellInvestmentAssetV2( msg.sender, _investmentId, _tokenAmount, _minPrice, nil, true ); } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, abi.encode( _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellInvestmentAssetV2( _manager, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ); } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_stake > 0); require(isKyberToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Add investment to list userInvestments[_sender].push( Investment({ tokenAddress: _tokenAddress, cycleNumber: cycleNumber, stake: _stake, tokenAmount: 0, buyPrice: 0, sellPrice: 0, buyTime: now, buyCostInUSDC: 0, isSold: false }) ); // Invest uint256 investmentId = investmentsCount(_sender).sub(1); __handleInvestment( _sender, investmentId, 0, _maxPrice, true, _calldata, _useKyber ); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; // Emit event __emitCreatedInvestmentEvent(_sender, investmentId); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public nonReentrant during(CyclePhase.Manage) { require(msg.sender == _sender || msg.sender == address(this)); Investment storage investment = userInvestments[_sender][_investmentId]; require( investment.buyPrice > 0 && investment.cycleNumber == cycleNumber && !investment.isSold ); require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount); // Create new investment for leftover tokens bool isPartialSell = false; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); if (_tokenAmount != investment.tokenAmount) { isPartialSell = true; __createInvestmentForLeftovers( _sender, _investmentId, _tokenAmount ); __emitCreatedInvestmentEvent( _sender, investmentsCount(_sender).sub(1) ); } // Update investment info investment.isSold = true; // Sell asset ( uint256 actualDestAmount, uint256 actualSrcAmount ) = __handleInvestment( _sender, _investmentId, _minPrice, uint256(-1), false, _calldata, _useKyber ); __sellInvestmentUpdate( _sender, _investmentId, stakeOfSoldTokens, actualDestAmount ); } function __sellInvestmentUpdate( address _sender, uint256 _investmentId, uint256 stakeOfSoldTokens, uint256 actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; // Return staked RepToken uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stakeOfSoldTokens, investment.sellPrice, investment.buyPrice ); __returnStake(receiveRepTokenAmount, stakeOfSoldTokens); // Record risk taken in investment __recordRisk(_sender, investment.stake, investment.buyTime); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add( actualDestAmount ); // Emit event __emitSoldInvestmentEvent( _sender, _investmentId, receiveRepTokenAmount, actualDestAmount ); } function __emitSoldInvestmentEvent( address _sender, uint256 _investmentId, uint256 _receiveRepTokenAmount, uint256 _actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; emit SoldInvestment( cycleNumber, _sender, _investmentId, investment.tokenAddress, _receiveRepTokenAmount, investment.sellPrice, _actualDestAmount ); } function __createInvestmentForLeftovers( address _sender, uint256 _investmentId, uint256 _tokenAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); // calculate the part of original USDC cost attributed to the sold tokens uint256 soldBuyCostInUSDC = investment .buyCostInUSDC .mul(_tokenAmount) .div(investment.tokenAmount); userInvestments[_sender].push( Investment({ tokenAddress: investment.tokenAddress, cycleNumber: cycleNumber, stake: investment.stake.sub(stakeOfSoldTokens), tokenAmount: investment.tokenAmount.sub(_tokenAmount), buyPrice: investment.buyPrice, sellPrice: 0, buyTime: investment.buyTime, buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC), isSold: false }) ); // update the investment object being sold investment.tokenAmount = _tokenAmount; investment.stake = stakeOfSoldTokens; investment.buyCostInUSDC = soldBuyCostInUSDC; } function __emitCreatedInvestmentEvent(address _sender, uint256 _id) internal { Investment storage investment = userInvestments[_sender][_id]; emit CreatedInvestment( cycleNumber, _sender, _id, investment.tokenAddress, investment.stake, investment.buyPrice, investment.buyCostInUSDC, investment.tokenAmount ); } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, abi.encode( _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createCompoundOrder( _manager, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ); } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, abi.encode(_orderId, _minPrice, _maxPrice), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice); } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, abi.encode(_orderId, _repayAmountInUSDC), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC); } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_minPrice <= _maxPrice); require(_stake > 0); require(isCompoundToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Create compound order and execute uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div( cToken.totalSupply() ); CompoundOrder order = __createCompoundOrder( _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); usdc.safeApprove(address(order), 0); usdc.safeApprove(address(order), collateralAmountInUSDC); order.executeOrder(_minPrice, _maxPrice); // Add order to list userCompoundOrders[_sender].push(address(order)); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; __emitCreatedCompoundOrderEvent( _sender, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } function __emitCreatedCompoundOrderEvent( address _sender, address order, bool _orderType, address _tokenAddress, uint256 _stake, uint256 collateralAmountInUSDC ) internal { // Emit event emit CreatedCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Sell order (uint256 inputAmount, uint256 outputAmount) = order.sellOrder( _minPrice, _maxPrice ); // Return staked RepToken uint256 stake = order.stake(); uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stake, outputAmount, inputAmount ); __returnStake(receiveRepTokenAmount, stake); // Record risk taken __recordRisk(_sender, stake, order.buyTime()); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount); // Emit event emit SoldCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), order.orderType(), order.compoundTokenAddr(), receiveRepTokenAmount, outputAmount ); } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Repay loan order.repayLoan(_repayAmountInUSDC); // Emit event emit RepaidCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _repayAmountInUSDC ); } function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public during(CyclePhase.Intermission) nonReentrant { CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]); order.emergencyExitTokens(_tokenAddr, _receiver); } function getReceiveRepTokenAmount( uint256 stake, uint256 output, uint256 input ) public pure returns (uint256 _amount) { if (output >= input) { // positive ROI, simply return stake * (1 + ROI) return stake.mul(output).div(input); } else { // negative ROI uint256 absROI = input.sub(output).mul(PRECISION).div(input); if (absROI <= ROI_PUNISH_THRESHOLD) { // ROI better than -10%, no punishment return stake.mul(output).div(input); } else if ( absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD ) { // ROI between -10% and -25%, punish // return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5))) return stake .mul( PRECISION.sub( ROI_PUNISH_SLOPE.mul(absROI).sub( ROI_PUNISH_NEG_BIAS ) ) ) .div(PRECISION); } else { // ROI greater than 25%, burn all stake return 0; } } } /** * @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading * @param _investmentId the ID of the investment to be handled * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade * @param _buy whether to buy or sell the given investment * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function __handleInvestment( address _sender, uint256 _investmentId, uint256 _minPrice, uint256 _maxPrice, bool _buy, bytes memory _calldata, bool _useKyber ) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) { Investment storage investment = userInvestments[_sender][_investmentId]; address token = investment.tokenAddress; // Basic trading uint256 dInS; // price of dest token denominated in src token uint256 sInD; // price of src token denominated in dest token if (_buy) { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token) ); } else { // 1inch trading ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token), _calldata ); } require(_minPrice <= dInS && dInS <= _maxPrice); investment.buyPrice = dInS; investment.tokenAmount = _actualDestAmount; investment.buyCostInUSDC = _actualSrcAmount; } else { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( ERC20Detailed(token), investment.tokenAmount, usdc ); } else { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( ERC20Detailed(token), investment.tokenAmount, usdc, _calldata ); } require(_minPrice <= sInD && sInD <= _maxPrice); investment.sellPrice = sInD; } } /** * @notice Separated from createCompoundOrder() to avoid stack too deep error */ function __createCompoundOrder( bool _orderType, // True for shorting, false for longing address _tokenAddress, uint256 _stake, uint256 _collateralAmountInUSDC ) internal returns (CompoundOrder) { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); uint256 loanAmountInUSDC = _collateralAmountInUSDC .mul(COLLATERAL_RATIO_MODIFIER) .div(PRECISION) .mul(factory.getMarketCollateralFactor(_tokenAddress)) .div(PRECISION); CompoundOrder order = factory.createOrder( _tokenAddress, cycleNumber, _stake, _collateralAmountInUSDC, loanAmountInUSDC, _orderType ); return order; } /** * @notice Returns stake to manager after investment is sold, including reward/penalty based on performance */ function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake) internal { require(cToken.destroyTokens(address(this), _stake)); require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount)); } /** * @notice Records risk taken in a trade based on stake and time of investment */ function __recordRisk( address _sender, uint256 _stake, uint256 _buyTime ) internal { _riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle( _sender, cycleNumber ) .add(_stake.mul(now.sub(_buyTime))); } } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic2 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Deposit & Withdraw */ function depositEther(address _referrer) public payable { bytes memory nil; depositEtherAdvanced(true, nil, _referrer); } /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositEtherAdvanced( bool _useKyber, bytes memory _calldata, address _referrer ) public payable nonReentrant notReadyForUpgrade { // Buy USDC with ETH uint256 actualUSDCDeposited; uint256 actualETHDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade( ETH_TOKEN_ADDRESS, msg.value, usdc ); } else { (, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade( ETH_TOKEN_ADDRESS, msg.value, usdc, _calldata ); } // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualUSDCDeposited, now ); } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. * @param _referrer the referrer's address */ function depositUSDC(uint256 _usdcAmount, address _referrer) public nonReentrant notReadyForUpgrade { usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount); // Register investment __deposit(_usdcAmount, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, _usdcAmount, _usdcAmount, now ); } function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { bytes memory nil; depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes memory _calldata, address _referrer ) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into USDC uint256 actualUSDCDeposited; uint256 actualTokenDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade( token, _tokenAmount, usdc ); } else { (, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade( token, _tokenAmount, usdc, _calldata ); } // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualUSDCDeposited, now ); } function withdrawEther(uint256 _amountInUSDC) external { bytes memory nil; withdrawEtherAdvanced(_amountInUSDC, true, nil); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public nonReentrant during(CyclePhase.Intermission) { // Buy ETH uint256 actualETHWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS ); } else { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualUSDCWithdrawn, now ); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) external nonReentrant during(CyclePhase.Intermission) { __withdraw(_amountInUSDC); // Transfer USDC to user usdc.safeTransfer(msg.sender, _amountInUSDC); // Emit event emit Withdraw( cycleNumber, msg.sender, USDC_ADDR, _amountInUSDC, _amountInUSDC, now ); } function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { bytes memory nil; withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil); } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert USDC into desired tokens uint256 actualTokenWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, token ); } else { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, token, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualUSDCWithdrawn, now ); } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC); __register(donationInUSDC); } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 receivedUSDC; // trade ETH for USDC (, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); require( _token != address(0) && _token != address(ETH_TOKEN_ADDRESS) && _token != USDC_ADDR ); ERC20Detailed token = ERC20Detailed(_token); require(token.totalSupply() > 0); token.safeTransferFrom(msg.sender, address(this), _donationInTokens); uint256 receivedUSDC; (, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount) public during(CyclePhase.Intermission) nonReentrant onlyOwner { require(isPermissioned); // mint REP for msg.sender require(cToken.generateTokens(_manager, _reptokenAmount)); // Set risk fallback base stake _baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add( _reptokenAmount ); // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[_manager] = cycleNumber; // emit events emit Register(_manager, 0, _reptokenAmount); } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (, , uint256 actualUSDCReceived, ) = __oneInchTrade( token, getBalance(token, address(this)), usdc, _calldata ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public during(CyclePhase.Intermission) nonReentrant { // Load order info require(_orderAddress != address(0)); CompoundOrder order = CompoundOrder(_orderAddress); require(order.isSold() == false && order.cycleNumber() < cycleNumber); // Sell short order // Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract uint256 beforeUSDCBalance = usdc.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub( beforeUSDCBalance ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Registers `msg.sender` as a manager. * @param _donationInUSDC the amount of USDC to be used for registration */ function __register(uint256 _donationInUSDC) internal { require( cToken.balanceOf(msg.sender) == 0 && userInvestments[msg.sender].length == 0 && userCompoundOrders[msg.sender].length == 0 ); // each address can only join once // mint REP for msg.sender uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice); require(cToken.generateTokens(msg.sender, repAmount)); // Set risk fallback base stake _baseRiskStakeFallback[msg.sender] = repAmount; // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[msg.sender] = cycleNumber; // keep USDC in the fund totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC); // emit events emit Register(msg.sender, _donationInUSDC, repAmount); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC * @param _referrer The deposit referrer */ function __deposit(uint256 _depositUSDCAmount, address _referrer) internal { // Register investment and give shares uint256 shareAmount; if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { uint256 usdcDecimals = getDecimals(usdc); shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals); } else { shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); } require(sToken.generateTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add( _depositUSDCAmount ); // Handle peakReferralToken if (peakReward.canRefer(msg.sender, _referrer)) { peakReward.refer(msg.sender, _referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { require( peakReferralToken.generateTokens(actualReferrer, shareAmount) ); } } /** * @notice Handles deposits by burning PeakDeFi Shares & updating total funds. * @param _withdrawUSDCAmount The amount of the withdrawal in USDC */ function __withdraw(uint256 _withdrawUSDCAmount) internal { // Burn Shares uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); require(sToken.destroyTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount); // Handle peakReferralToken address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { uint256 balance = peakReferralToken.balanceOf(actualReferrer); uint256 burnReferralTokenAmount = shareAmount > balance ? balance : shareAmount; require( peakReferralToken.destroyTokens( actualReferrer, burnReferralTokenAmount ) ); } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; contract PeakDeFiLogic3 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Next phase transition handler * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public nonReentrant { require( now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)]) ); if (isInitialized == false) { // first cycle of this smart contract deployment // check whether ready for starting cycle isInitialized = true; require(proxyAddr != address(0)); // has initialized proxy require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete require(hasInitializedTokenListings); // has initialized token listings // execute initialization function __init(); require( previousVersion == address(0) || (previousVersion != address(0) && getBalance(usdc, address(this)) > 0) ); // has transfered assets from previous version } else { // normal phase changing if (cyclePhase == CyclePhase.Intermission) { require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading // Update total funds at management phase's beginning totalFundsAtManagePhaseStart = totalFundsInUSDC; // reset number of managers onboarded managersOnboardedThisCycle = 0; } else if (cyclePhase == CyclePhase.Manage) { // Burn any RepToken left in PeakDeFiFund's account require( cToken.destroyTokens( address(this), cToken.balanceOf(address(this)) ) ); // Pay out commissions and fees uint256 profit = 0; uint256 usdcBalanceAtManagePhaseStart = totalFundsAtManagePhaseStart.add(totalCommissionLeft); if ( getBalance(usdc, address(this)) > usdcBalanceAtManagePhaseStart ) { profit = getBalance(usdc, address(this)).sub( usdcBalanceAtManagePhaseStart ); } totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Calculate manager commissions uint256 commissionThisCycle = COMMISSION_RATE .mul(profit) .add(ASSET_FEE_RATE.mul(totalFundsInUSDC)) .div(PRECISION); _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(commissionThisCycle); // account for penalties totalCommissionLeft = totalCommissionLeft.add( commissionThisCycle ); // Calculate referrer commissions uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE .mul(profit) .mul(peakReferralToken.totalSupply()) .div(sToken.totalSupply()) .div(PRECISION); _peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle( cycleNumber ) .add(peakReferralCommissionThisCycle); peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft .add(peakReferralCommissionThisCycle); totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Give the developer PeakDeFi shares inflation funding uint256 devFunding = devFundingRate .mul(sToken.totalSupply()) .div(PRECISION); require(sToken.generateTokens(devFundingAccount, devFunding)); // Emit event emit TotalCommissionPaid( cycleNumber, totalCommissionOfCycle(cycleNumber) ); emit PeakReferralTotalCommissionPaid( cycleNumber, peakReferralTotalCommissionOfCycle(cycleNumber) ); _managePhaseEndBlock[cycleNumber] = block.number; // Clear/update upgrade related data if (nextVersion == address(this)) { // The developer proposed a candidate, but the managers decide to not upgrade at all // Reset upgrade process delete nextVersion; delete hasFinalizedNextVersion; } if (nextVersion != address(0)) { hasFinalizedNextVersion = true; emit FinalizedNextVersion(cycleNumber, nextVersion); } // Start new cycle cycleNumber = cycleNumber.add(1); } cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2)); } startTimeOfCyclePhase = now; // Reward caller if they're a manager if (cToken.balanceOf(msg.sender) > 0) { require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD)); } emit ChangedPhase( cycleNumber, uint256(cyclePhase), now, totalFundsInUSDC ); } /** * @notice Initializes several important variables after smart contract upgrade */ function __init() internal { _managePhaseEndBlock[cycleNumber.sub(1)] = block.number; // load values from previous version totalCommissionLeft = previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionLeft(); totalFundsInUSDC = getBalance(usdc, address(this)).sub( totalCommissionLeft ); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public onlyOwner notReadyForUpgrade during(CyclePhase.Intermission) nonReentrant returns (bool _success) { if (_candidate == address(0) || _candidate == address(this)) { return false; } nextVersion = _candidate; emit DeveloperInitiatedUpgrade(cycleNumber, _candidate); return true; } /** Commission functions */ /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public view returns (uint256 _commission, uint256 _penalty) { if (lastCommissionRedemption(_manager) >= cycleNumber) { return (0, 0); } uint256 cycle = lastCommissionRedemption(_manager) > 0 ? lastCommissionRedemption(_manager) : 1; uint256 cycleCommission; uint256 cyclePenalty; for (; cycle < cycleNumber; cycle++) { (cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle); _commission = _commission.add(cycleCommission); _penalty = _penalty.add(cyclePenalty); } } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public view returns (uint256 _commission, uint256 _penalty) { if (hasRedeemedCommissionForCycle(_manager, _cycle)) { return (0, 0); } // take risk into account uint256 baseRepTokenBalance = cToken.balanceOfAt( _manager, managePhaseEndBlock(_cycle.sub(1)) ); uint256 baseStake = baseRepTokenBalance == 0 ? baseRiskStakeFallback(_manager) : baseRepTokenBalance; if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) { return (0, 0); } uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle) .mul(PRECISION) .div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold riskTakenProportion = riskTakenProportion > PRECISION ? PRECISION : riskTakenProportion; // max proportion is 1 uint256 fullCommission = totalCommissionOfCycle(_cycle) .mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle))) .div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle))); _commission = fullCommission.mul(riskTakenProportion).div(PRECISION); _penalty = fullCommission.sub(_commission); } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __redeemCommissionForCycle(_cycle); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __redeemCommission() internal returns (uint256 _commission) { require(lastCommissionRedemption(msg.sender) < cycleNumber); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = lastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _hasRedeemedCommissionForCycle[msg.sender][i] = true; } _lastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __redeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!hasRedeemedCommissionForCycle(msg.sender, _cycle)); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionOfAt(msg.sender, _cycle); _hasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(_cycle, msg.sender, _commission); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC */ function __deposit(uint256 _depositUSDCAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { require(sToken.generateTokens(msg.sender, _depositUSDCAmount)); } else { require( sToken.generateTokens( msg.sender, _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ) ) ); } totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); } /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public view returns (uint256 _commission) { if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) { return (0); } uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0 ? peakReferralLastCommissionRedemption(_referrer) : 1; uint256 cycleCommission; for (; cycle < cycleNumber; cycle++) { (cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle); _commission = _commission.add(cycleCommission); } } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public view returns (uint256 _commission) { _commission = peakReferralTotalCommissionOfCycle(_cycle) .mul( peakReferralToken.balanceOfAt( _referrer, managePhaseEndBlock(_cycle) ) ) .div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle))); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __peakReferralRedeemCommission(); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommission() internal returns (uint256 _commission) { require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber); _commission = peakReferralCommissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = peakReferralLastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true; } _peakReferralLastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle)); _commission = peakReferralCommissionOfAt(msg.sender, _cycle); _peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/Comptroller.sol"; contract TestCERC20 is CERC20 { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public constant MAX_UINT = 2 ** 256 - 1; address public _underlying; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address __underlying, address _comptrollerAddr) public { _underlying = __underlying; COMPTROLLER = Comptroller(_comptrollerAddr); } function mint(uint mintAmount) external returns (uint) { ERC20Detailed token = ERC20Detailed(_underlying); require(token.transferFrom(msg.sender, address(this), mintAmount)); _balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION)); return 0; } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, redeemAmount)); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, amount)); return 0; } function repayBorrow(uint amount) external returns (uint) { // accept repayment ERC20Detailed token = ERC20Detailed(_underlying); uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount; require(token.transferFrom(msg.sender, address(this), repayAmount)); // subtract from borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount); return 0; } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function underlying() external view returns (address) { return _underlying; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } } pragma solidity 0.5.17; import "./TestCERC20.sol"; contract TestCERC20Factory { mapping(address => address) public createdTokens; event CreatedToken(address underlying, address cToken); function newToken(address underlying, address comptroller) public returns(address) { require(createdTokens[underlying] == address(0)); TestCERC20 token = new TestCERC20(underlying, comptroller); createdTokens[underlying] = address(token); emit CreatedToken(underlying, address(token)); return address(token); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/CEther.sol"; import "../interfaces/Comptroller.sol"; contract TestCEther is CEther { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address _comptrollerAddr) public { COMPTROLLER = Comptroller(_comptrollerAddr); } function mint() external payable { _balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION)); } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); msg.sender.transfer(redeemAmount); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset msg.sender.transfer(amount); return 0; } function repayBorrow() external payable { _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value); } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestComptroller is Comptroller { using SafeMath for uint; uint256 internal constant PRECISION = 10 ** 18; mapping(address => address[]) public getAssetsIn; uint256 internal collateralFactor = 2 * PRECISION / 3; constructor() public {} function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) { uint[] memory errors = new uint[](cTokens.length); for (uint256 i = 0; i < cTokens.length; i = i.add(1)) { getAssetsIn[msg.sender].push(cTokens[i]); errors[i] = 0; } return errors; } function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) { return (true, collateralFactor); } } pragma solidity 0.5.17; import "../interfaces/KyberNetwork.sol"; import "../Utils.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable { mapping(address => uint256) public priceInUSDC; constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner { priceInUSDC[_token] = _priceInUSDC; } function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate) { uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); return (result, result); } function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint /*minConversionRate*/, address /*walletId*/, bytes calldata /*hint*/ ) external payable returns(uint) { require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount); if (address(src) == address(ETH_TOKEN_ADDRESS)) { require(srcAmount == msg.value); } else { require(src.transferFrom(msg.sender, address(this), srcAmount)); } if (address(dest) == address(ETH_TOKEN_ADDRESS)) { destAddress.transfer(calcDestAmount(src, srcAmount, dest)); } else { require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest))); } return calcDestAmount(src, srcAmount, dest); } function calcDestAmount( ERC20Detailed src, uint srcAmount, ERC20Detailed dest ) internal view returns (uint destAmount) { return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestPriceOracle is PriceOracle, Ownable { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; address public CETH_ADDR; mapping(address => uint256) public priceInUSD; constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSD[_tokens[i]] = _pricesInUSD[i]; } CETH_ADDR = _cETH; } function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner { priceInUSD[_token] = _priceInUSD; } function getUnderlyingPrice(address _cToken) external view returns (uint) { if (_cToken == CETH_ADDR) { return priceInUSD[_cToken]; } CERC20 cToken = CERC20(_cToken); ERC20Detailed underlying = ERC20Detailed(cToken.underlying()); return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals())); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title An ERC20 token used for testing. * @author Zefram Lou (Zebang Liu) */ contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor(string memory name, string memory symbol, uint8 decimals) public ERC20Detailed(name, symbol, decimals) {} } pragma solidity 0.5.17; import "./TestToken.sol"; contract TestTokenFactory { mapping(bytes32 => address) public createdTokens; event CreatedToken(string symbol, address addr); function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) { bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); require(createdTokens[symbolHash] == address(0)); TestToken token = new TestToken(name, symbol, decimals); token.addMinter(msg.sender); token.renounceMinter(); createdTokens[symbolHash] = address(token); emit CreatedToken(symbol, address(token)); return address(token); } function getToken(string memory symbol) public view returns(address) { return createdTokens[keccak256(abi.encodePacked(symbol))]; } } pragma solidity 0.5.17; contract TestUniswapOracle { function update() external returns (bool success) { return true; } function consult(address token, uint256 amountIn) external view returns (uint256 amountOut) { return 3 * 10**5; // 1 PEAK = 0.30 USDC } }
This function makes it easy to read the `allowed[]` map _owner The address of the account that owns the token _spender The address of the account able to transfer the tokens return Amount of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; }
15,851,799
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract FinToken is StandardToken { address public owner; string public constant name = "FIN Token"; string public constant symbol = "FIN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 2623304 * (10 ** uint256(decimals)); mapping (address => bool) internal verificatorAddresses; mapping (address => bool) internal verifiedAddresses; event AddVerificator(address indexed verificator); event RemoveVerificator(address indexed verificator); event AddVerified(address indexed verificatorAddress, address indexed verified); event RemoveVerified(address indexed verificatorAddress, address indexed verified); event Mint(address indexed to, uint256 amount); modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyVerificator() { require(isVerificator(msg.sender)); _; } modifier onlyVerified(address _from, address _to) { require(isVerified(_from)); require(isVerified(_to)); _; } function FinToken() public { owner = msg.sender; totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function addVerificatorAddress(address addr) public onlyOwner { verificatorAddresses[addr] = true; emit AddVerificator(addr); } function removeVerificatorAddress(address addr) public onlyOwner { delete verificatorAddresses[addr]; emit RemoveVerificator(addr); } function isVerificator(address addr) public constant returns (bool) { return verificatorAddresses[addr]; } function addVerifiedAddress(address addr) public onlyVerificator { verifiedAddresses[addr] = true; emit AddVerified(msg.sender, addr); } function removeVerifiedAddress(address addr) public onlyVerificator { delete verifiedAddresses[addr]; emit RemoveVerified(msg.sender, addr); } function isVerified(address addr) public constant returns (bool) { return verifiedAddresses[addr]; } function transfer(address _to, uint256 _value) public onlyVerified(msg.sender, _to) returns (bool) { super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public onlyVerified(_from, _to) returns (bool) { super.transferFrom(_from, _to, _value); } }
Gets the balance of the specified address. _owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address./
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
1,114,554
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IPit.sol"; /// @title A pooltogether yield source for viper pit token /// @author Steffel Fenix, coco-sha contract ViperPitSource is IYieldSource, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; /// @notice Interface of the viperPit contract IPit public immutable viperPit; /// @notice Interface for the viper token IERC20 public immutable viperAddr; mapping(address => uint256) public balances; /// @notice Emitted when asset tokens are redeemed from the yield source event RedeemedToken( address indexed from, uint256 shares, uint256 amount ); /// @notice Emitted when asset tokens are supplied to the yield source event SuppliedTokenTo( address indexed from, uint256 shares, uint256 amount, address indexed to ); constructor(IPit _viperPit, IERC20 _viperAddr) public ReentrancyGuard() { require( address(_viperPit) != address(0), "ViperPitSource/viperPit-not-zero-address" ); require( address(_viperAddr) != address(0), "ViperPitSource/viperAddr-not-zero-address" ); viperPit = _viperPit; viperAddr = _viperAddr; _viperAddr.safeApprove(address(_viperPit), type(uint256).max); } /// @notice Approve VIPER to spend infinite viperPit (xViper) /// @dev Emergency function to re-approve max amount if approval amount dropped too low /// @return true if operation is successful function approveMaxAmount() external returns (bool) { address _viperPitAddress = address(viperPit); IERC20 viper = viperAddr; uint256 allowance = viper.allowance(address(this), _viperPitAddress); viper.safeIncreaseAllowance(_viperPitAddress, type(uint256).max.sub(allowance)); return true; } /// @notice Returns the ERC20 asset token used for deposits. /// @return The ERC20 asset token function depositToken() external view override returns (address) { return address(viperAddr); } /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function balanceOfToken(address addr) external override returns (uint256) { if (balances[addr] == 0) return 0; uint256 totalShares = viperPit.totalSupply(); uint256 viperPitBalance = viperAddr.balanceOf(address(viperPit)); return balances[addr].mul(viperPitBalance).div(totalShares); } /// @notice Allows assets to be supplied on other user's behalf using the `to` param. /// @param amount The amount of `token()` to be supplied /// @param to The user whose balance will receive the tokens function supplyTokenTo(uint256 amount, address to) external override nonReentrant { IPit pit = viperPit; IERC20 viper = viperAddr; viper.safeTransferFrom(msg.sender, address(this), amount); uint256 beforeBalance = pit.balanceOf(address(this)); pit.enter(amount); uint256 afterBalance = pit.balanceOf(address(this)); uint256 balanceDiff = afterBalance.sub(beforeBalance); balances[to] = balances[to].add(balanceDiff); emit SuppliedTokenTo(msg.sender, balanceDiff, amount, to); } /// @notice Redeems tokens from the yield source to the msg.sender, it burns yield bearing tokens and returns token to the sender. /// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above. /// @dev The maxiumum that can be called for token() is calculated by balanceOfToken() above. /// @return The actual amount of tokens that were redeemed. This may be different from the amount passed due to the fractional math involved. function redeemToken(uint256 amount) external override nonReentrant returns (uint256) { IPit pit = viperPit; IERC20 viper = viperAddr; uint256 totalShares = pit.totalSupply(); if (totalShares == 0) return 0; uint256 viperPitBalance = viper.balanceOf(address(pit)); if (viperPitBalance == 0) return 0; uint256 sushiBeforeBalance = viper.balanceOf(address(this)); uint256 requiredShares = ((amount.mul(totalShares).add(totalShares))).div(viperPitBalance); if (requiredShares == 0) return 0; uint256 requiredSharesBalance = requiredShares.sub(1); pit.leave(requiredSharesBalance); uint256 sushiAfterBalance = viper.balanceOf(address(this)); uint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance); balances[msg.sender] = balances[msg.sender].sub(requiredSharesBalance); viper.safeTransfer(msg.sender, sushiBalanceDiff); emit RedeemedToken(msg.sender, requiredSharesBalance, amount); return (sushiBalanceDiff); } }
Returns the total balance (in asset tokens). This includes the deposits and interest. return The underlying balance of asset tokens
function balanceOfToken(address addr) external override returns (uint256) { if (balances[addr] == 0) return 0; uint256 totalShares = viperPit.totalSupply(); uint256 viperPitBalance = viperAddr.balanceOf(address(viperPit)); return balances[addr].mul(viperPitBalance).div(totalShares); }
14,033,291
./full_match/4/0x540BCa81D630590a2212eA0F8ECBE8e0C618e071/sources/contracts/GambleFinal.sol
function to stakestoring the stakerstoring playerstoring amount staked by player
function stake() public payable stakingConditions returns(bool){ player = msg.sender; players.push(player); playerAmount[player] = msg.value; }
12,352,702
pragma solidity ^0.4.24; import "../access/roles/ListerRole.sol"; import "../access/roles/UnlisterRole.sol"; /** * @title AddressList * * @dev Contract for maintaining a list of addresses, e.g. for a blacklist or whitelist. * This contract inherits the Lister contract to use RBAC for administering accounts that can add to the list. * This contract inherits the Unlister contract to use RBAC for administering accounts that can remove from the list. */ contract AddressList is ListerRole, UnlisterRole { /** Whether or not this contract has been initialized. */ bool private _initialized; /** Name of this AddressList, used as a display attribute only. */ string private _name; /** Mapping of each address to whether or not they're on the list. */ mapping (address => bool) private _onList; /** Event emitted whenever an address is added to the list. */ event AddressAdded(address indexed account); /** Event emitted whenever an address is removed from the list. */ event AddressRemoved(address indexed account); /** * @dev Initialize function used in place of a constructor. * This is required over a normal due to the constructor caveat when using proxy contracts. * * @param name The name of the address list */ function initialize(string name) external { // Assert that the contract hasn't already been initialized require(!_initialized); // Provide the account initializing the contract with access to the owner role super._addOwner(msg.sender); // Set the name of the list _name = name; // Set the initialized state to true so the contract cannot be initialized again _initialized = true; } /** * @return True if the contract has been initialized, otherwise false */ function initialized() external view returns (bool) { return _initialized; } /** * @return The name of the AddressList */ function name() external view returns (string) { return _name; } /** * @dev Query whether the the given `account` is on this list or not. * * @param account The account address being queried * @return True if the account is on the list, otherwise false */ function onList(address account) external view returns (bool) { return _onList[account]; } /** * @dev Update the name of the list. * Callable by an account with the listerAdmin role. * * @param newName The new display name of the list */ function updateName(string newName) external onlyListerAdmin { _name = newName; } /** * @dev Add the given `account` to the list. * Callable by an account with the lister role. * * @param account Account to add to the list */ function addAddress(address account) external onlyLister { _addAddress(account); } /** * @dev Remove the given `account` from the list. * Callable by an account with the unlister role. * * @param account Account to remove from the list */ function removeAddress(address account) external onlyUnlister { _removeAddress(account); } /** * @dev Replace the `previousAccount` in the list with the `newAccount`. * Callable by an account with both the lister role and unlister role. * * @param previousAccount Account to remove from the list * @param newAccount Account to add to the list */ function replaceAddress(address previousAccount, address newAccount) external onlyLister onlyUnlister { _removeAddress(previousAccount); _addAddress(newAccount); } /** * @dev Internal function that adds the given `account` to the `_onList` mapping. * Emits an AddressAdded event. * * @param account The account being added to the list */ function _addAddress(address account) internal { // Throw if the account is already on the list require(!_onList[account]); _onList[account] = true; emit AddressAdded(account); } /** * @dev Internal function that removes the given `account` from the `_onList` mapping. * Emits an AddressRemoved event. * * @param account The account being removed from the list */ function _removeAddress(address account) internal { // Throw if the account is not on the list require(_onList[account]); _onList[account] = false; emit AddressRemoved(account); } }
Add the given `account` to the list. Callable by an account with the lister role. account Account to add to the list/
function addAddress(address account) external onlyLister { _addAddress(account); }
6,386,725
./partial_match/3/0xC073C78BC6f38cD6725FC1331d9e9Bf431db037B/sources/matrixplay.sol
dev_stak_address.transfer(devfund[msg.sender].total_fund);
function transferToDevFund() external { require(dev_stak_address != address(0),'Development Fund Module Not Started'); require(devfund[msg.sender].total_fund > 0,"Didnt Have Enough Amount in Development Fund"); ERC20 tokenContract = ERC20(usdt_address); tokenContract.transfer(dev_stak_address,devfund[msg.sender].total_fund); emit DevFundTransfer(msg.sender,devfund[msg.sender].total_fund); devfund[msg.sender].total_transfer += devfund[msg.sender].total_fund; devfund[msg.sender].last_transfer = devfund[msg.sender].total_fund; current_dev_fun -= devfund[msg.sender].total_fund; devfund[msg.sender].total_fund = 0 ; }
5,126,371
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/thirdparty/loopring-wallet/ILoopringWalletV2.sol // Taken from: https://github.com/Loopring/protocols/tree/master/packages/hebao_v2/contracts/iface/ILoopringWalletV2.sol // Copyright 2017 Loopring Technology Limited. /// @title Loopring SmartWallet V2 interface /// @author Brecht Devos - <[email protected]> abstract contract ILoopringWalletV2 { /// @dev Initializes the smart wallet. /// @param owner The wallet owner address. /// @param guardians The initial wallet guardians. /// @param quota The initial wallet quota. /// @param inheritor The inheritor of the wallet. /// @param feeRecipient The address receiving the fee for creating the wallet. /// @param feeToken The token to use for the fee payment. /// @param feeAmount The amount of tokens paid to the fee recipient. function initialize( address owner, address[] calldata guardians, uint quota, address inheritor, address feeRecipient, address feeToken, uint feeAmount ) external virtual; /// @dev Returns the timestamp the wallet was created. /// @return The timestamp the wallet was created. function getCreationTimestamp() public view virtual returns (uint64); /// @dev Returns the current wallet owner. /// @return The current wallet owner. function getOwner() public view virtual returns (address); } // File: contracts/thirdparty/Create2.sol // Taken from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/970f687f04d20e01138a3e8ccf9278b1d4b3997b/contracts/utils/Create2.sol /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. Note that * a contract cannot be deployed twice using the same salt. */ function deploy(bytes32 salt, bytes memory bytecode) internal returns (address payable) { address payable addr; // solhint-disable-next-line no-inline-assembly assembly { addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "CREATE2_FAILED"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecode` * or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) { return computeAddress(salt, bytecode, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes memory bytecodeHash, address deployer) internal pure returns (address) { bytes32 bytecodeHashHash = keccak256(bytecodeHash); bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash) ); return address(bytes20(_data << 96)); } } // File: contracts/thirdparty/proxies/WalletProxy.sol // Taken from: https://github.com/gnosis/safe-contracts/blob/development/contracts/proxies/GnosisSafeProxy.sol /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain /// @author Richard Meissner - <[email protected]> interface IProxy { function masterCopy() external view returns (address); } /// @title WalletProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract WalletProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. fallback() payable external { // solium-disable-next-line security/no-inline-assembly assembly { let _masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, _masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas(), _masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // File: contracts/thirdparty/loopring-wallet/WalletDeploymentLib.sol // Taken from: https://github.com/Loopring/protocols/tree/master/packages/hebao_v2/contracts/base/WalletDeploymentLib.sol // Copyright 2017 Loopring Technology Limited. /// @title WalletDeploymentLib /// @dev Functionality to compute wallet addresses and to deploy wallets /// @author Brecht Devos - <[email protected]> contract WalletDeploymentLib { address public immutable walletImplementation; string public constant WALLET_CREATION = "WALLET_CREATION"; constructor( address _walletImplementation ) { walletImplementation = _walletImplementation; } function getWalletCode() public view returns (bytes memory) { return hex"608060405234801561001057600080fd5b5060405161016f38038061016f8339818101604052602081101561003357600080fd5b50516001600160a01b03811661007a5760405162461bcd60e51b815260040180806020018281038252602481526020018061014b6024913960400191505060405180910390fd5b600080546001600160a01b039092166001600160a01b031990921691909117905560a2806100a96000396000f3fe6080604052600073ffffffffffffffffffffffffffffffffffffffff8154167fa619486e0000000000000000000000000000000000000000000000000000000082351415604e57808252602082f35b3682833781823684845af490503d82833e806067573d82fd5b503d81f3fea2646970667358221220676404d5a2e50e328cc18fc786619f9629ae43d7ff695286c941717f0a1541e564736f6c63430007060033496e76616c6964206d617374657220636f707920616464726573732070726f76696465640000000000000000000000004b16684de50ebcc60fd54b0a5fd1ccfdc940bb27"; } function computeWalletSalt( address owner, uint salt ) public pure returns (bytes32) { return keccak256( abi.encodePacked( WALLET_CREATION, owner, salt ) ); } function _deploy( address owner, uint salt ) internal returns (address payable wallet) { wallet = Create2.deploy( computeWalletSalt(owner, salt), getWalletCode() ); } function _computeWalletAddress( address owner, uint salt, address deployer ) internal view returns (address) { return Create2.computeAddress( computeWalletSalt(owner, salt), getWalletCode(), deployer ); } } // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/lib/ERC1271.sol // Copyright 2017 Loopring Technology Limited. abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32); } // File: contracts/lib/SignatureUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's last byte indicates /// the signature's type. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(signHash, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { if (signer == address(0)) { return false; } return signer.isContract()? verifyERC1271Signature(signHash, signer, signature): verifyEOASignature(signHash, signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function verifyEOASignature( bytes32 signHash, address signer, bytes memory signature ) private pure returns (bool success) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); // Strip off the last byte of the signature by updating the length assembly { mstore(signature, signatureTypeOffset) } if (signatureType == SignatureType.EIP_712) { success = (signer == recoverECDSASigner(signHash, signature)); } else if (signatureType == SignatureType.ETH_SIGN) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash) ); success = (signer == recoverECDSASigner(hash, signature)); } else { success = false; } // Restore the signature length assembly { mstore(signature, add(signatureTypeOffset, 1)) } return success; } function verifyERC1271Signature( bytes32 signHash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271.isValidSignature.selector, signHash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION, NFT_MINT, // L2 NFT mint or L1-to-L2 NFT deposit NFT_DATA } enum NftType { ERC1155, ERC721 } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; uint public constant NFT_TOKEN_ID_START = 2 ** 15; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint weightAMM; uint storageRoot; } struct Nft { address minter; // Minter address for a L2 mint or // the NFT's contract address in the case of a L1-to-L2 NFT deposit. NftType nftType; address token; uint256 nftID; uint8 creatorFeeBips; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; ExchangeData.Nft nft; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; Block block; uint txIndex; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) // The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; // Duplicated loopring address address loopringAddr; // AMM fee bips uint8 ammFeeBips; // Enable/Disable `onchainTransferFrom` bool allowOnchainTransferFrom; // owner => NFT type => token address => nftID => Deposit mapping (address => mapping (NftType => mapping (address => mapping(uint256 => Deposit)))) pendingNFTDeposits; // owner => minter => NFT type => token address => nftID => amount withdrawable // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (address => mapping (NftType => mapping (address => mapping(uint256 => uint))))) amountWithdrawableNFT; } } // File: contracts/core/iface/IExchangeV3.sol // Copyright 2017 Loopring Technology Limited. /// @title IExchangeV3 /// @dev Note that Claimable and RentrancyGuard are inherited here to /// ensure all data members are declared on IExchangeV3 to make it /// easy to support upgradability through proxies. /// /// Subclasses of this contract must NOT define constructor to /// initialize data. /// /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract IExchangeV3 is Claimable { // -- Events -- event ExchangeCloned( address exchangeAddress, address owner, bytes32 genesisMerkleRoot ); event TokenRegistered( address token, uint16 tokenId ); event Shutdown( uint timestamp ); event WithdrawalModeActivated( uint timestamp ); event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event DepositRequested( address from, address to, address token, uint16 tokenId, uint96 amount ); event NFTDepositRequested( address from, address to, uint8 nftType, address token, uint256 nftID, uint96 amount ); event ForcedWithdrawalRequested( address owner, uint16 tokenID, uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); event TransactionApproved( address owner, bytes32 transactionHash ); // -- Initialization -- /// @dev Initializes this exchange. This method can only be called once. /// @param loopring The LoopringV3 contract address. /// @param owner The owner of this exchange. /// @param genesisMerkleRoot The initial Merkle tree state. function initialize( address loopring, address owner, bytes32 genesisMerkleRoot ) virtual external; /// @dev Initialized the agent registry contract used by the exchange. /// Can only be called by the exchange owner once. /// @param agentRegistry The agent registry contract to be used function setAgentRegistry(address agentRegistry) external virtual; /// @dev Gets the agent registry contract used by the exchange. /// @return the agent registry contract function getAgentRegistry() external virtual view returns (IAgentRegistry); /// Can only be called by the exchange owner once. /// @param depositContract The deposit contract to be used function setDepositContract(address depositContract) external virtual; /// @dev refresh the blockVerifier contract which maybe changed in loopringV3 contract. function refreshBlockVerifier() external virtual; /// @dev Gets the deposit contract used by the exchange. /// @return the deposit contract function getDepositContract() external virtual view returns (IDepositContract); // @dev Exchange owner withdraws fees from the exchange. // @param token Fee token address // @param feeRecipient Fee recipient address function withdrawExchangeFees( address token, address feeRecipient ) external virtual; // -- Constants -- /// @dev Returns a list of constants used by the exchange. /// @return constants The list of constants. function getConstants() external virtual pure returns(ExchangeData.Constants memory); // -- Mode -- /// @dev Returns hether the exchange is in withdrawal mode. /// @return Returns true if the exchange is in withdrawal mode, else false. function isInWithdrawalMode() external virtual view returns (bool); /// @dev Returns whether the exchange is shutdown. /// @return Returns true if the exchange is shutdown, else false. function isShutdown() external virtual view returns (bool); // -- Tokens -- /// @dev Registers an ERC20 token for a token id. Note that different exchanges may have /// different ids for the same ERC20 token. /// /// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH), /// and 3 is reserved for Loopring Token (LRC). /// /// This function is only callable by the exchange owner. /// /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function registerToken( address tokenAddress ) external virtual returns (uint16 tokenID); /// @dev Returns the id of a registered token. /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function getTokenID( address tokenAddress ) external virtual view returns (uint16 tokenID); /// @dev Returns the address of a registered token. /// @param tokenID The token's ID in this exchanges. /// @return tokenAddress The token's address function getTokenAddress( uint16 tokenID ) external virtual view returns (address tokenAddress); // -- Stakes -- /// @dev Gets the amount of LRC the owner has staked onchain for this exchange. /// The stake will be burned if the exchange does not fulfill its duty by /// processing user requests in time. Please note that order matching may potentially /// performed by another party and is not part of the exchange's duty. /// /// @return The amount of LRC staked function getExchangeStake() external virtual view returns (uint); /// @dev Withdraws the amount staked for this exchange. /// This can only be done if the exchange has been correctly shutdown: /// - The exchange owner has shutdown the exchange /// - All deposit requests are processed /// - All funds are returned to the users (merkle root is reset to initial state) /// /// Can only be called by the exchange owner. /// /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient ) external virtual returns (uint amountLRC); /// @dev Can by called by anyone to burn the stake of the exchange when certain /// conditions are fulfilled. /// /// Currently this will only burn the stake of the exchange if /// the exchange is in withdrawal mode. function burnExchangeStake() external virtual; // -- Blocks -- /// @dev Gets the current Merkle root of this exchange's virtual blockchain. /// @return The current Merkle root. function getMerkleRoot() external virtual view returns (bytes32); /// @dev Gets the height of this exchange's virtual blockchain. The block height for a /// new exchange is 1. /// @return The virtual blockchain height which is the index of the last block. function getBlockHeight() external virtual view returns (uint); /// @dev Gets some minimal info of a previously submitted block that's kept onchain. /// A DEX can use this function to implement a payment receipt verification /// contract with a challange-response scheme. /// @param blockIdx The block index. function getBlockInfo(uint blockIdx) external virtual view returns (ExchangeData.BlockInfo memory); /// @dev Sumbits new blocks to the rollup blockchain. /// /// This function can only be called by the exchange operator. /// /// @param blocks The blocks being submitted /// - blockType: The type of the new block /// - blockSize: The number of onchain or offchain requests/settlements /// that have been processed in this block /// - blockVersion: The circuit version to use for verifying the block /// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain /// - data: The data for this block /// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e., /// the multihash of the IPFS file that contains the block data. function submitBlocks(ExchangeData.Block[] calldata blocks) external virtual; /// @dev Gets the number of available forced request slots. /// @return The number of available slots. function getNumAvailableForcedSlots() external virtual view returns (uint); // -- Deposits -- /// @dev Deposits Ether or ERC20 tokens to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param amount The amount of tokens to deposit /// @param extraData Optional extra data used by the deposit contract function deposit( address from, address to, address tokenAddress, uint96 amount, bytes calldata extraData ) external virtual payable; /// @dev Deposits an NFT to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftID The token type 'id`. /// @param amount The amount of tokens to deposit. /// @param extraData Optional extra data used by the deposit contract. function depositNFT( address from, address to, ExchangeData.NftType nftType, address tokenAddress, uint256 nftID, uint96 amount, bytes calldata extraData ) external virtual; /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The amount of tokens pending. function getPendingDepositAmount( address owner, address tokenAddress ) public virtual view returns (uint96); /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. /// @return The amount of tokens pending. function getPendingNFTDepositAmount( address owner, address tokenAddress, ExchangeData.NftType nftType, uint256 nftID ) public virtual view returns (uint96); // -- Withdrawals -- /// @dev Submits an onchain request to force withdraw Ether, ERC20 and NFT tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenID The tokenID to withdraw from /// @param accountID The address the account in the Merkle tree. function forceWithdrawByTokenID( address owner, uint16 tokenID, uint32 accountID ) external virtual payable; /// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param accountID The address the account in the Merkle tree. function forceWithdraw( address owner, address tokenAddress, uint32 accountID ) external virtual payable; /// @dev Checks if a forced withdrawal is pending for an account balance. /// @param accountID The accountID of the account to check. /// @param token The token address /// @return True if a request is pending, false otherwise function isForcedWithdrawalPending( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the /// protocol fees account. The complete balance is always withdrawn. /// /// Anyone can request a withdrawal of the protocol fees. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param tokenAddress The address of the token, use `0x0` for Ether. function withdrawProtocolFees( address tokenAddress ) external virtual payable; /// @dev Gets the time the protocol fee for a token was last withdrawn. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The time the protocol fee was last withdrawn. function getProtocolFeeLastWithdrawnTime( address tokenAddress ) external virtual view returns (uint); /// @dev Allows anyone to withdraw funds for a specified user using the balances stored /// in the Merkle tree. The funds will be sent to the owner of the acount. /// /// Can only be used in withdrawal mode (i.e. when the owner has stopped /// committing blocks and is not able to commit any more blocks). /// /// This will NOT modify the onchain merkle root! The merkle root stored /// onchain will remain the same after the withdrawal. We store if the user /// has withdrawn the balance in State.withdrawnInWithdrawMode. /// /// @param merkleProof The Merkle inclusion proof function withdrawFromMerkleTree( ExchangeData.MerkleProof calldata merkleProof ) external virtual; /// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`. /// @param accountID The accountID of the balance to check. /// @param token The token address /// @return True if it was already withdrawn, false otherwise function isWithdrawnInWithdrawalMode( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address function withdrawFromDepositRequest( address owner, address token ) external virtual; /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. function withdrawFromNFTDepositRequest( address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) external virtual; /// @dev Allows withdrawing funds after a withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// Tokens and owners must have the same size. /// /// @param owners The addresses of the account the withdrawal was done for. /// @param tokens The token addresses function withdrawFromApprovedWithdrawals( address[] calldata owners, address[] calldata tokens ) external virtual; /// @dev Allows withdrawing funds after an NFT withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// All input arrays must have the same size. /// /// @param owners The addresses of the accounts the withdrawal was done for. /// @param minters The addresses of the minters. /// @param nftTypes The NFT token addresses types /// @param tokens The token addresses /// @param nftIDs The token ids function withdrawFromApprovedWithdrawalsNFT( address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) external virtual; /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @return The amount withdrawable function getAmountWithdrawable( address owner, address token ) external virtual view returns (uint); /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawalsNFT`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The NFT token address types /// @param nftID The token id /// @param minter The NFT minter /// @return The amount withdrawable function getAmountWithdrawableNFT( address owner, address token, ExchangeData.NftType nftType, uint256 nftID, address minter ) external virtual view returns (uint); /// @dev Notifies the exchange that the owner did not process a forced request. /// If this is indeed the case, the exchange will enter withdrawal mode. /// /// Can be called by anyone. /// /// @param accountID The accountID the forced request was made for /// @param tokenID The tokenID of the the forced request function notifyForcedRequestTooOld( uint32 accountID, uint16 tokenID ) external virtual; /// @dev Allows a withdrawal to be done to an adddresss that is different /// than initialy specified in the withdrawal request. This can be used to /// implement functionality like fast withdrawals. /// /// This function can only be called by an agent. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. /// @param newRecipient The new recipient address of the withdrawal. function setWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external virtual; /// @dev Gets the withdrawal recipient. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. function getWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID ) external virtual view returns (address); /// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance /// the user has set for the exchange. This way the user only needs to approve a single exchange contract /// for all exchange/agent features, which allows for a more seamless user experience. /// /// This function can only be called by an agent. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function onchainTransferFrom( address from, address to, address token, uint amount ) external virtual; /// @dev Allows an agent to approve a rollup tx. /// /// This function can only be called by an agent. /// /// @param owner The owner of the account /// @param txHash The hash of the transaction function approveTransaction( address owner, bytes32 txHash ) external virtual; /// @dev Allows an agent to approve multiple rollup txs. /// /// This function can only be called by an agent. /// /// @param owners The account owners /// @param txHashes The hashes of the transactions function approveTransactions( address[] calldata owners, bytes32[] calldata txHashes ) external virtual; /// @dev Checks if a rollup tx is approved using the tx's hash. /// /// @param owner The owner of the account that needs to authorize the tx /// @param txHash The hash of the transaction /// @return True if the tx is approved, else false function isTransactionApproved( address owner, bytes32 txHash ) external virtual view returns (bool); // -- Admins -- /// @dev Sets the max time deposits have to wait before becoming withdrawable. /// @param newValue The new value. /// @return The old value. function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32); /// @dev Returns the max time deposits have to wait before becoming withdrawable. /// @return The value. function getMaxAgeDepositUntilWithdrawable() external virtual view returns (uint32); /// @dev Shuts down the exchange. /// Once the exchange is shutdown all onchain requests are permanently disabled. /// When all requirements are fulfilled the exchange owner can withdraw /// the exchange stake with withdrawStake. /// /// Note that the exchange can still enter the withdrawal mode after this function /// has been invoked successfully. To prevent entering the withdrawal mode before the /// the echange stake can be withdrawn, all withdrawal requests still need to be handled /// for at least MIN_TIME_IN_SHUTDOWN seconds. /// /// Can only be called by the exchange owner. /// /// @return success True if the exchange is shutdown, else False function shutdown() external virtual returns (bool success); /// @dev Gets the protocol fees for this exchange. /// @return syncedAt The timestamp the protocol fees were last updated /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee /// @return previousTakerFeeBips The previous protocol taker fee /// @return previousMakerFeeBips The previous protocol maker fee function getProtocolFeeValues() external virtual view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); /// @dev Gets the domain separator used in this exchange. function getDomainSeparator() external virtual view returns (bytes32); /// @dev set amm pool feeBips value. function setAmmFeeBips(uint8 _feeBips) external virtual; /// @dev get amm pool feeBips value. function getAmmFeeBips() external virtual view returns (uint8); } // File: contracts/amm/libamm/IAmmSharedConfig.sol // Copyright 2017 Loopring Technology Limited. interface IAmmSharedConfig { function maxForcedExitAge() external view returns (uint); function maxForcedExitCount() external view returns (uint); function forcedExitFee() external view returns (uint); } // File: contracts/amm/libamm/AmmData.sol // Copyright 2017 Loopring Technology Limited. /// @title AmmData library AmmData { uint public constant POOL_TOKEN_BASE = 100 * (10 ** 8); uint public constant POOL_TOKEN_MINTED_SUPPLY = uint96(-1); enum PoolTxType { NOOP, JOIN, EXIT } struct PoolConfig { address sharedConfig; address exchange; string poolName; uint32 accountID; address[] tokens; uint96[] weights; uint8 feeBips; string tokenSymbol; } struct PoolJoin { address owner; uint96[] joinAmounts; uint32[] joinStorageIDs; uint96 mintMinAmount; uint96 fee; uint32 validUntil; } struct PoolExit { address owner; uint96 burnAmount; uint32 burnStorageID; // for pool token withdrawal from user to the pool uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee. uint96 fee; uint32 validUntil; } struct PoolTx { PoolTxType txType; bytes data; bytes signature; } struct Token { address addr; uint96 weight; uint16 tokenID; } struct Context { // functional parameters uint txIdx; // AMM pool state variables bytes32 domainSeparator; uint32 accountID; uint16 poolTokenID; uint8 feeBips; uint totalSupply; Token[] tokens; uint96[] tokenBalancesL2; } struct State { // Pool token state variables string poolName; string symbol; uint _totalSupply; mapping(address => uint) balanceOf; mapping(address => mapping(address => uint)) allowance; mapping(address => uint) nonces; // AMM pool state variables IAmmSharedConfig sharedConfig; Token[] tokens; // The order of the following variables important to minimize loads bytes32 exchangeDomainSeparator; bytes32 domainSeparator; IExchangeV3 exchange; uint32 accountID; uint16 poolTokenID; uint8 feeBips; address exchangeOwner; uint64 shutdownTimestamp; uint16 forcedExitCount; // A map from a user to the forced exit. mapping (address => PoolExit) forcedExit; mapping (bytes32 => bool) approvedTx; } } // File: contracts/aux/access/IBlockReceiver.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockReceiver /// @author Brecht Devos - <[email protected]> abstract contract IBlockReceiver { function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external virtual; } // File: contracts/lib/EIP712.sol // Copyright 2017 Loopring Technology Limited. library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainSeparator, bytes32 dataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainSeparator, dataHash ) ); } } // File: contracts/thirdparty/SafeCast.sol // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/lib/FloatUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for floats /// @author Brecht Devos - <[email protected]> library FloatUtil { using MathUint for uint; using SafeCast for uint; // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits for the exponent /// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent) /// @return value The decoded integer value. function decodeFloat( uint f, uint numBits ) internal pure returns (uint96 value) { if (f == 0) { return 0; } uint numBitsMantissa = numBits.sub(5); uint exponent = f >> numBitsMantissa; // log2(10**77) = 255.79 < 256 require(exponent <= 77, "EXPONENT_TOO_LARGE"); uint mantissa = f & ((1 << numBitsMantissa) - 1); value = mantissa.mul(10 ** exponent).toUint96(); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 11 bits mantissa /// @return value The decoded integer value. function decodeFloat16( uint16 f ) internal pure returns (uint96) { uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 19 bits mantissa /// @return value The decoded integer value. function decodeFloat24( uint24 f ) internal pure returns (uint96) { uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } } // File: contracts/core/impl/libexchange/ExchangeSignatures.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeSignatures. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeSignatures { using SignatureUtil for bytes32; function requireAuthorizedTx( ExchangeData.State storage S, address signer, bytes memory signature, bytes32 txHash ) internal // inline call { require(signer != address(0), "INVALID_SIGNER"); // Verify the signature if one is provided, otherwise fall back to an approved tx if (signature.length > 0) { require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE"); } else { require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED"); delete S.approvedTx[signer][txHash]; } } } // File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AccountUpdateTransaction /// @author Brecht Devos - <[email protected]> library AccountUpdateTransaction { using BytesUtil for bytes; using FloatUtil for uint16; using ExchangeSignatures for ExchangeData.State; bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256( "AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)" ); struct AccountUpdate { address owner; uint32 accountID; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint publicKey; uint32 validUntil; uint32 nonce; } // Auxiliary data for each account update struct AccountUpdateAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the account update AccountUpdate memory accountUpdate; readTx(data, offset, accountUpdate); AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData)); // Fill in withdrawal data missing from DA accountUpdate.validUntil = auxData.validUntil; accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee; // Validate require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate); // Check onchain authorization S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AccountUpdate memory accountUpdate ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional offset require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the data from the tx data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. accountUpdate.owner = data.toAddressUnsafe(_offset); _offset += 20; accountUpdate.accountID = data.toUint32Unsafe(_offset); _offset += 4; accountUpdate.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; accountUpdate.publicKey = data.toUintUnsafe(_offset); _offset += 32; accountUpdate.nonce = data.toUint32Unsafe(_offset); _offset += 4; } function hashTx( bytes32 DOMAIN_SEPARATOR, AccountUpdate memory accountUpdate ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( ACCOUNTUPDATE_TYPEHASH, accountUpdate.owner, accountUpdate.accountID, accountUpdate.feeTokenID, accountUpdate.maxFee, accountUpdate.publicKey, accountUpdate.validUntil, accountUpdate.nonce ) ) ); } } // File: contracts/aux/agents/LoopringWalletAgent.sol // Copyright 2017 Loopring Technology Limited. /// @title LoopringWalletAgent /// @dev Agent to allow authorizing L2 transactions using an undeployed Loopring Smart Wallet /// @author Brecht Devos - <[email protected]> contract LoopringWalletAgent is WalletDeploymentLib, IBlockReceiver { using AddressUtil for address; using SignatureUtil for bytes32; // Maximum amount of time this agent can still authorize transactions // approved by the initial wallet owner after the wallet has been deployed. uint public constant MAX_TIME_VALID_AFTER_CREATION = 7 days; address public immutable deployer; IExchangeV3 public immutable exchange; bytes32 public immutable EXCHANGE_DOMAIN_SEPARATOR; struct WalletSignatureData { bytes signature; uint96 maxFee; uint32 validUntil; address walletOwner; uint salt; } constructor( address _walletImplementation, address _deployer, IExchangeV3 _exchange ) WalletDeploymentLib(_walletImplementation) { deployer = _deployer; exchange = _exchange; EXCHANGE_DOMAIN_SEPARATOR = _exchange.getDomainSeparator(); } // Allows authorizing transactions in an independent transaction function approveTransactionsFor( address[] calldata wallets, bytes32[] calldata txHashes, bytes[] calldata signatures ) external virtual { require(txHashes.length == wallets.length, "INVALID_DATA"); require(signatures.length == wallets.length, "INVALID_DATA"); // Verify the signatures for (uint i = 0; i < wallets.length; i++) { WalletSignatureData memory data = abi.decode(signatures[i], (WalletSignatureData)); require( _canInitialOwnerAuthorizeTransactions(wallets[i], msg.sender, data.salt) || _isUsableSignatureForWallet( wallets[i], txHashes[i], data ), "INVALID_SIGNATURE" ); } // Approve the transactions on the exchange exchange.approveTransactions(wallets, txHashes); } // Allow transactions to be authorized while submitting a block function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external override virtual { _beforeBlockSubmission(txsData, callbackData); } // Returns true if the signature can be used for authorizing the transaction function isUsableSignatureForWallet( address wallet, bytes32 hash, bytes memory signature ) public view returns (bool) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); return _isUsableSignatureForWallet(wallet, hash, data); } // Returns true if just the signature is valid (but it may have expired) function isValidSignatureForWallet( address wallet, bytes32 hash, bytes memory signature ) public view returns (bool) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); return _isValidSignatureForWallet(wallet, hash, data); } // Returns the timestamp up until the signature can be used function getSignatureExpiry( address wallet, bytes32 hash, bytes memory signature ) public view returns (uint) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); if (!_isValidSignatureForWallet(wallet, hash, data)) { return 0; } else { return getInitialOwnerExpiry(wallet); } } // Returns the timestamp up until the initial owner can authorize transactions function getInitialOwnerExpiry( address walletAddress ) public view returns (uint) { // Always allowed when the smart wallet hasn't been deployed yet if (!walletAddress.isContract()) { return type(uint).max; } ILoopringWalletV2 wallet = ILoopringWalletV2(walletAddress); // Allow the initial wallet owner to sign transactions after deployment for some limited time return wallet.getCreationTimestamp() + MAX_TIME_VALID_AFTER_CREATION; } // == Internal Functions == function _beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) internal view returns (AccountUpdateTransaction.AccountUpdate memory accountUpdate) { WalletSignatureData memory data = abi.decode(callbackData, (WalletSignatureData)); // Read the AccountUpdate transaction AccountUpdateTransaction.readTx(txsData, 0, accountUpdate); // Fill in withdrawal data missing from DA accountUpdate.validUntil = data.validUntil; accountUpdate.maxFee = data.maxFee == 0 ? accountUpdate.fee : data.maxFee; // Validate require(block.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the transaction hash bytes32 txHash = AccountUpdateTransaction.hashTx(EXCHANGE_DOMAIN_SEPARATOR, accountUpdate); // Verify the signature require( _isUsableSignatureForWallet( accountUpdate.owner, txHash, data ), "INVALID_SIGNATURE" ); // Make sure we have consumed exactly the expected number of transactions require(txsData.length == ExchangeData.TX_DATA_AVAILABILITY_SIZE, "INVALID_NUM_TXS"); } function _isUsableSignatureForWallet( address wallet, bytes32 hash, WalletSignatureData memory data ) internal view returns (bool) { // Verify that the signature is valid and the initial owner is still allowed // to authorize transactions for the wallet. return _isValidSignatureForWallet(wallet, hash, data) && _isInitialOwnerUsable(wallet); } function _isValidSignatureForWallet( address wallet, bytes32 hash, WalletSignatureData memory data ) internal view returns (bool) { // Verify that the account owner is the initial owner of the smart wallet // and that the signature is a valid signature from the initial owner. return _isInitialOwner(wallet, data.walletOwner, data.salt) && hash.verifySignature(data.walletOwner, data.signature); } function _canInitialOwnerAuthorizeTransactions( address wallet, address walletOwner, uint salt ) internal view returns (bool) { // Verify that the initial owner is the owner of the wallet // and can still be used to authorize transactions return _isInitialOwner(wallet, walletOwner, salt) && _isInitialOwnerUsable(wallet); } function _isInitialOwnerUsable( address wallet ) internal view virtual returns (bool) { return block.timestamp <= getInitialOwnerExpiry(wallet); } function _isInitialOwner( address wallet, address walletOwner, uint salt ) internal view returns (bool) { return _computeWalletAddress(walletOwner, salt, deployer) == wallet; } } // File: contracts/aux/agents/DestroyableWalletAgent.sol // Copyright 2017 Loopring Technology Limited. /// @title DestroyableWalletAgent /// @dev Agent that allows setting up accounts that can easily be rendered unusable /// @author Brecht Devos - <[email protected]> contract DestroyableWalletAgent is LoopringWalletAgent { struct WalletData { uint32 accountID; bool destroyed; } mapping(address => WalletData) public walletData; constructor( address _walletImplementation, address _deployer, IExchangeV3 exchange ) LoopringWalletAgent(_walletImplementation, _deployer, exchange) {} function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external override { AccountUpdateTransaction.AccountUpdate memory accountUpdate; accountUpdate = LoopringWalletAgent._beforeBlockSubmission(txsData, callbackData); WalletData storage wallet = walletData[accountUpdate.owner]; if (wallet.accountID == 0) { // First use of this wallet, store the accountID wallet.accountID = accountUpdate.accountID; } else { // Only allow a single account on L2 to ever sign L2 transactions // for this wallet address require( wallet.accountID == accountUpdate.accountID, "ACCOUNT_ALREADY_EXISTS_FOR_WALLET" ); } // Destroy the wallet if the EdDSA public key is set to 0 if (accountUpdate.publicKey == 0) { wallet.destroyed = true; } } /// @dev Computes the destructable wallet address /// @param owner The owner. /// @param salt A salt. /// @return The wallet address function computeWalletAddress( address owner, uint salt ) public view returns (address) { return _computeWalletAddress( owner, salt, deployer ); } /// @dev Checks if the wallet can still be used /// @param wallet The wallet address. /// @return Returns true if destroyed, else false function isDestroyed( address wallet ) public view returns (bool) { return walletData[wallet].destroyed; } // Disable `approveTransactionsFor` function approveTransactionsFor( address[] calldata /*wallets*/, bytes32[] calldata /*txHashes*/, bytes[] calldata /*signatures*/ ) external override pure { revert("UNSUPPORTED"); } // == Internal Functions == function _isInitialOwnerUsable( address wallet ) internal view override returns (bool) { // Also disallow the owner to use the wallet when destroyed return LoopringWalletAgent._isInitialOwnerUsable(wallet) && !isDestroyed(wallet); } }
Checks if the wallet can still be used wallet The wallet address. return Returns true if destroyed, else false
function isDestroyed( address wallet ) public view returns (bool) { return walletData[wallet].destroyed; }
1,427,412
./full_match/1/0x6e788C5B65A77f7869F0B843d977d411f7d2E209/sources/contracts/TheAnomalies.sol
Update the royalty percentage (500 = 5%)/
function setRoyaltyInfo(uint96 newRoyaltyPercentage) public onlyOwner { _setDefaultRoyalty(treasuryAddress, newRoyaltyPercentage); }
17,009,600
./partial_match/1/0x5113A3Dd866A3EE8E973FC764cC380e6F07416Ef/sources/contracts/NFTCollection.sol
Runs on every transfer.
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (transfersRestricted && from != address(0) && to != address(0)) { require( hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "NFTCollection: Transfers are restricted to or from TRANSFER_ROLE holders" ); } }
4,151,082
./full_match/11155111/0x043d0c1a4fd26A4713BF1f53135C56fb35eF1274/sources/project_/contracts/MekeRouter02.sol
ADD LIQUIDITY create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = MekeLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = MekeLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = MekeLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
3,798,093
./full_match/1/0x94D792E07216796Cb235E328823199fb8DA3C911/sources/src/auction/IAuction.sol
IAuction Rohan Kulkarni The external Auction events, errors, and functions
interface IAuction is IUUPS, IOwnable, IPausable { event AuctionBid(uint256 tokenId, address bidder, uint256 amount, bool extended, uint256 endTime); event AuctionSettled(uint256 tokenId, address winner, uint256 amount); event AuctionCreated(uint256 tokenId, uint256 startTime, uint256 endTime); event DurationUpdated(uint256 duration); event ReservePriceUpdated(uint256 reservePrice); event MinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); event TimeBufferUpdated(uint256 timeBuffer); error INVALID_TOKEN_ID(); error AUCTION_OVER(); error AUCTION_NOT_STARTED(); error AUCTION_ACTIVE(); error AUCTION_SETTLED(); error RESERVE_PRICE_NOT_MET(); error MINIMUM_BID_NOT_MET(); error INSOLVENT(); error ONLY_MANAGER(); error FAILING_WETH_TRANSFER(); error AUCTION_CREATE_FAILED_TO_LAUNCH(); function initialize( address token, address founder, address treasury, uint256 duration, uint256 reservePrice ) external; function createBid(uint256 tokenId) external payable; function settleCurrentAndCreateNewAuction() external; function settleAuction() external; function pause() external; function unpause() external; function duration() external view returns (uint256); function reservePrice() external view returns (uint256); function timeBuffer() external view returns (uint256); function minBidIncrement() external view returns (uint256); function setDuration(uint256 duration) external; function setReservePrice(uint256 reservePrice) external; function setTimeBuffer(uint256 timeBuffer) external; function setMinimumBidIncrement(uint256 percentage) external; function treasury() external returns (address); pragma solidity 0.8.16; import { IUUPS } from "../lib/interfaces/IUUPS.sol"; import { IOwnable } from "../lib/interfaces/IOwnable.sol"; import { IPausable } from "../lib/interfaces/IPausable.sol"; }
3,052,217
// SPDX-License-Identifier: MIT /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Copyright (c) 2020 Ditto Money Copyright (c) 2021 Goes Up Higher Copyright (c) 2021 Cryptographic Ultra Money Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.6.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface ILP { function sync() external; } abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) {return _lockTime;} function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @title CUM ERC20 token * @dev * The goal of CUM is to be hardest money. * Based on the Ampleforth protocol. */ contract CUM is Context, ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; mapping (address => bool) private _isExcludedFromFee; address BURN_ADDRESS = 0x0000000000000000000000000000000000000001; address public liq_locker; uint256 public _liquidityFee = 4; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _burnFee = 2; uint256 private _previousBurnFee = _burnFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public numTokensSellToAddToLiquidity = 66666 * 10**2 * 10**DECIMALS; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SetLPEvent(address lpAddress); event SetLLEvent(address llAddress); event AddressExcluded(address exAddress); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } event LogRebase(uint256 indexed epoch, uint256 totalSupply); // Used for authentication address public master; // LP atomic sync address public lp; ILP public lpContract; modifier onlyMaster() { require(msg.sender == master); _; } // Only the owner can transfer tokens in the initial phase. // This is allow the AMM listing to happen in an orderly fashion. bool public initialDistributionFinished; mapping (address => bool) allowTransfer; modifier initialDistributionLock { require(initialDistributionFinished || isOwner() || allowTransfer[msg.sender]); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 66666 * 10**6 * 10**DECIMALS; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMaster returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(-supplyDelta)); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } numTokensSellToAddToLiquidity = _totalSupply.div(10000); _gonsPerFragment = TOTAL_GONS.div(_totalSupply); lpContract.sync(); emit LogRebase(epoch, _totalSupply); return _totalSupply; } constructor() ERC20Detailed("Cryptographic Ultra Money", "CUM", uint8(DECIMALS)) public { _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonBalances[msg.sender] = TOTAL_GONS; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[BURN_ADDRESS] = true; initialDistributionFinished = false; emit Transfer(address(0x0), msg.sender, _totalSupply); } /** * @notice Sets a new master */ function setMaster(address masterAddress) external onlyOwner returns (uint256) { master = masterAddress; } /** * @notice Sets contract LP address */ function setLP(address lpAddress) external onlyOwner returns (uint256) { lp = lpAddress; lpContract = ILP(lp); emit SetLPEvent(lp); } /** * @notice Sets Liquidity Locker address */ function setLiqLocker(address llAddress) external onlyOwner returns (uint256) { liq_locker = llAddress; _isExcludedFromFee[liq_locker] = true; emit SetLLEvent(liq_locker); } /** * @notice Adds excluded address */ function excludeFromFeeAdd(address exAddress) external onlyOwner returns (uint256) { _isExcludedFromFee[exAddress] = true; emit AddressExcluded(exAddress); } function excludeFromFeeRemove(address exAddress) external onlyOwner returns (uint256) { _isExcludedFromFee[exAddress] = false; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } function _approve(address owner, address spender, uint256 value) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowedFragments[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) initialDistributionLock override returns (bool) { _transfer(_msgSender(), to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param sender The address you want to send tokens from. * @param recipient The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address sender, address recipient, uint256 value) public validRecipient(recipient) override returns (bool) { _transfer(sender, recipient, value); _approve(sender, _msgSender(), _allowedFragments[sender][_msgSender()].sub(value)); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public initialDistributionLock override returns (bool) { _allowedFragments[_msgSender()][spender] = value; emit Approval(_msgSender(), spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external initialDistributionLock returns (bool) { _allowedFragments[_msgSender()][spender] = _allowedFragments[_msgSender()][spender].add(addedValue); emit Approval(_msgSender(), spender, _allowedFragments[_msgSender()][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external initialDistributionLock returns (bool) { uint256 oldValue = _allowedFragments[_msgSender()][spender]; if (subtractedValue >= oldValue) { _allowedFragments[_msgSender()][spender] = 0; } else { _allowedFragments[_msgSender()][spender] = oldValue.sub(subtractedValue); } emit Approval(_msgSender(), spender, _allowedFragments[_msgSender()][spender]); return true; } function setInitialDistributionFinished() external onlyOwner { initialDistributionFinished = true; } function enableTransfer(address _addr) external onlyOwner { allowTransfer[_addr] = true; } function removeAllFee() private { if(_burnFee == 0 && _liquidityFee == 0) return; _previousBurnFee = _burnFee; _previousLiquidityFee = _liquidityFee; _burnFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _burnFee = _previousBurnFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function setBurnFeePercent(uint256 burnFee) external onlyOwner() { require(burnFee <= 10); _burnFee = burnFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 10); _liquidityFee = liquidityFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liq_locker, block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if(!takeFee) restoreAllFee(); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tBurn = calculateBurnFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tBurn).sub(tLiquidity); return (tTransferAmount, tBurn, tLiquidity); } function _transferBurn(uint256 tBurn) private { _gonBalances[BURN_ADDRESS] = _gonBalances[BURN_ADDRESS].add(tBurn); } function _takeLiquidity(uint256 tLiquidity) private { _gonBalances[address(this)] = _gonBalances[address(this)].add(tLiquidity); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 gonValue = tAmount.mul(_gonsPerFragment); (uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity) = _getTValues(gonValue); _gonBalances[sender] = _gonBalances[sender].sub(gonValue); _gonBalances[recipient] = _gonBalances[recipient].add(tTransferAmount); _transferBurn(tBurn); _takeLiquidity(tLiquidity); emit Transfer(sender, BURN_ADDRESS, tBurn.div(_gonsPerFragment)); emit Transfer(sender, address(this), tLiquidity.div(_gonsPerFragment)); emit Transfer(sender, recipient, tTransferAmount.div(_gonsPerFragment)); } }
Function to check the amount of tokens that an owner has allowed to a spender. owner_ The address which owns the funds. spender The address which will spend the funds. return The number of tokens still available for the spender./
function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; }
257,463
pragma solidity ^0.8.0; import "./__HPL_ERC20Burnable.sol"; import "../../interfaces/ITokenHook.sol"; import "../../lib/BlackholePrevention.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; contract HPLBase is Ownable, Initializable, __HPL_ERC20Burnable, BlackholePrevention { ITokenHook public tokenHook; address public stakingRewardTreasury; mapping(address => bool) public pancakePairs; event SetTokenHook(address caller, address tokenHook); event SetPancakePair(address caller, address pancakePair); event SetStaking(address caller, address stakingAddress); constructor() __HPL_ERC20("HappyLand.Finance", "HPL") {} function initialize( address _tokenReceiver, address _stakingRewardTreasury, address _tokenHook ) external initializer { //supply 400M _mint(_tokenReceiver, 400 * 1000000 * 10**decimals()); stakingRewardTreasury = _stakingRewardTreasury; tokenHook = ITokenHook(_tokenHook); } function setTokenHook(address _addr) external onlyOwner { tokenHook = ITokenHook(_addr); emit SetTokenHook(msg.sender, _addr); } function setStakingRewardTreasury(address _stakingRewardTreasury) external onlyOwner { require(stakingRewardTreasury != address(0), "null address"); stakingRewardTreasury = _stakingRewardTreasury; emit SetStaking(msg.sender, _stakingRewardTreasury); } function setPancakePairs(address[] calldata _pancakePairs, bool val) external onlyOwner { for (uint256 i = 0; i < _pancakePairs.length; i++) { require(_pancakePairs[i] != address(0), "null address"); pancakePairs[_pancakePairs[i]] = val; emit SetStaking(msg.sender, _pancakePairs[i]); } } function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); if (!pancakePairs[sender] && address(tokenHook) != address(0)) { tokenHook.addLiquidity(); } unchecked { _balances[sender] = senderBalance - amount; } if ( address(tokenHook) != address(0) && sender != address(tokenHook) && recipient != address(tokenHook) ) { ( uint256 stakeFee, uint256 liquidityFee, uint256 burnFee ) = tokenHook.getTransferFees(sender, recipient, amount); uint256 burnAmount = (amount * burnFee) / 10000; uint256 stakingRewardTreasuryAmount = (amount * stakeFee) / 10000; uint256 liquidityHolderAmount = (amount * liquidityFee) / 10000; //burn _totalSupply -= burnAmount; //treasury _balances[stakingRewardTreasury] += stakingRewardTreasuryAmount; //liquidityFee _balances[address(tokenHook)] += liquidityHolderAmount; _balances[recipient] += amount - burnAmount - stakingRewardTreasuryAmount - liquidityHolderAmount; emit Transfer(sender, address(0), burnAmount); emit Transfer( sender, stakingRewardTreasury, stakingRewardTreasuryAmount ); emit Transfer(sender, address(tokenHook), liquidityHolderAmount); emit Transfer( sender, recipient, amount - burnAmount - stakingRewardTreasuryAmount - liquidityHolderAmount ); } else { _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } _afterTokenTransfer(sender, recipient, amount); } //rescue loss token function withdrawEther(address payable receiver, uint256 amount) external virtual onlyOwner { _withdrawEther(receiver, amount); } function withdrawERC20( address payable receiver, address tokenAddress, uint256 amount ) external virtual onlyOwner { _withdrawERC20(receiver, tokenAddress, amount); } function withdrawERC721( address payable receiver, address tokenAddress, uint256 tokenId ) external virtual onlyOwner { _withdrawERC721(receiver, tokenAddress, tokenId); } }
burntreasuryliquidityFee
function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); if (!pancakePairs[sender] && address(tokenHook) != address(0)) { tokenHook.addLiquidity(); } unchecked { _balances[sender] = senderBalance - amount; } if ( address(tokenHook) != address(0) && sender != address(tokenHook) && recipient != address(tokenHook) ) { ( uint256 stakeFee, uint256 liquidityFee, uint256 burnFee ) = tokenHook.getTransferFees(sender, recipient, amount); uint256 burnAmount = (amount * burnFee) / 10000; uint256 stakingRewardTreasuryAmount = (amount * stakeFee) / 10000; uint256 liquidityHolderAmount = (amount * liquidityFee) / 10000; _totalSupply -= burnAmount; _balances[stakingRewardTreasury] += stakingRewardTreasuryAmount; _balances[address(tokenHook)] += liquidityHolderAmount; _balances[recipient] += amount - burnAmount - stakingRewardTreasuryAmount - liquidityHolderAmount; emit Transfer(sender, address(0), burnAmount); emit Transfer( sender, stakingRewardTreasury, stakingRewardTreasuryAmount ); emit Transfer(sender, address(tokenHook), liquidityHolderAmount); emit Transfer( sender, recipient, amount - burnAmount - stakingRewardTreasuryAmount - liquidityHolderAmount ); _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } _afterTokenTransfer(sender, recipient, amount); }
6,428,805
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title KYC * @dev KYC contract handles the white list for ASTCrowdsale contract * Only accounts registered in KYC contract can buy AST token. * Admins can register account, and the reason why */ contract KYC is Ownable { // check the address is registered for token sale mapping (address => bool) public registeredAddress; // check the address is admin of kyc contract mapping (address => bool) public admin; event Registered(address indexed _addr); event Unregistered(address indexed _addr); event NewAdmin(address indexed _addr); event ClaimedTokens(address _token, address owner, uint256 balance); /** * @dev check whether the address is registered for token sale or not. * @param _addr address */ modifier onlyRegistered(address _addr) { require(registeredAddress[_addr]); _; } /** * @dev check whether the msg.sender is admin or not */ modifier onlyAdmin() { require(admin[msg.sender]); _; } function KYC() { admin[msg.sender] = true; } /** * @dev set new admin as admin of KYC contract * @param _addr address The address to set as admin of KYC contract */ function setAdmin(address _addr) public onlyOwner { require(_addr != address(0) && admin[_addr] == false); admin[_addr] = true; NewAdmin(_addr); } /** * @dev register the address for token sale * @param _addr address The address to register for token sale */ function register(address _addr) public onlyAdmin { require(_addr != address(0) && registeredAddress[_addr] == false); registeredAddress[_addr] = true; Registered(_addr); } /** * @dev register the addresses for token sale * @param _addrs address[] The addresses to register for token sale */ function registerByList(address[] _addrs) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { require(_addrs[i] != address(0) && registeredAddress[_addrs[i]] == false); registeredAddress[_addrs[i]] = true; Registered(_addrs[i]); } } /** * @dev unregister the registered address * @param _addr address The address to unregister for token sale */ function unregister(address _addr) public onlyAdmin onlyRegistered(_addr) { registeredAddress[_addr] = false; Unregistered(_addr); } /** * @dev unregister the registered addresses * @param _addrs address[] The addresses to unregister for token sale */ function unregisterByList(address[] _addrs) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { require(registeredAddress[_addrs[i]]); registeredAddress[_addrs[i]] = false; Unregistered(_addrs[i]); } } function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(this.balance); return; } ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.2'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract ATC is MiniMeToken { mapping (address => bool) public blacklisted; bool public generateFinished; // @dev ATC constructor just parametrizes the MiniMeToken constructor function ATC(address _tokenFactory) MiniMeToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent "ATCon Token", // Token name 18, // Decimals "ATC", // Symbol false // Enable transfers ) {} function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { require(generateFinished == false); //check msg.sender (controller ??) return super.generateTokens(_owner, _amount); } function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { require(blacklisted[_from] == false); return super.doTransfer(_from, _to, _amount); } function finishGenerating() public onlyController returns (bool success) { generateFinished = true; return true; } function blacklistAccount(address tokenOwner) public onlyController returns (bool success) { blacklisted[tokenOwner] = true; return true; } function unBlacklistAccount(address tokenOwner) public onlyController returns (bool success) { blacklisted[tokenOwner] = false; return true; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable, SafeMath{ enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; mapping (address => uint256) public refunded; State public state; address[] public reserveWallet; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @dev This constructor sets the addresses of * 10 reserve wallets. * and forwarding it if crowdsale is successful. * @param _reserveWallet address[5] The addresses of reserve wallet. */ function RefundVault(address[] _reserveWallet) { state = State.Active; reserveWallet = _reserveWallet; } /** * @dev This function is called when user buy tokens. Only RefundVault * contract stores the Ether user sent which forwarded from crowdsale * contract. * @param investor address The address who buy the token from crowdsale. */ function deposit(address investor) onlyOwner payable { require(state == State.Active); deposited[investor] = add(deposited[investor], msg.value); } event Transferred(address _to, uint _value); /** * @dev This function is called when crowdsale is successfully finalized. */ function close() onlyOwner { require(state == State.Active); state = State.Closed; uint256 balance = this.balance; uint256 reserveAmountForEach = div(balance, reserveWallet.length); for(uint8 i = 0; i < reserveWallet.length; i++){ reserveWallet[i].transfer(reserveAmountForEach); Transferred(reserveWallet[i], reserveAmountForEach); } Closed(); } /** * @dev This function is called when crowdsale is unsuccessfully finalized * and refund is required. */ function enableRefunds() onlyOwner { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @dev This function allows for user to refund Ether. */ function refund(address investor) returns (bool) { require(state == State.Refunding); if (refunded[investor] > 0) { return false; } uint256 depositedValue = deposited[investor]; deposited[investor] = 0; refunded[investor] = depositedValue; investor.transfer(depositedValue); Refunded(investor, depositedValue); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } contract ATCCrowdSale is Ownable, SafeMath, Pausable { KYC public kyc; ATC public token; RefundVault public vault; address public presale; address public bountyAddress; //5% for bounty address public partnersAddress; //15% for community groups & partners address public ATCReserveLocker; //15% with 2 years lock address public teamLocker; // 15% with 2 years vesting struct Period { uint256 startTime; uint256 endTime; uint256 bonus; // used to calculate rate with bonus. ragne 0 ~ 15 (0% ~ 15%) } uint256 public baseRate; // 1 ETH = 1500 ATC uint256[] public additionalBonusAmounts; Period[] public periods; uint8 constant public MAX_PERIOD_COUNT = 8; uint256 public weiRaised; uint256 public maxEtherCap; uint256 public minEtherCap; mapping (address => uint256) public beneficiaryFunded; address[] investorList; mapping (address => bool) inInvestorList; address public ATCController; bool public isFinalized; uint256 public refundCompleted; bool public presaleFallBackCalled; uint256 public finalizedTime; bool public initialized; event CrowdSaleTokenPurchase(address indexed _investor, address indexed _beneficiary, uint256 _toFund, uint256 _tokens); event StartPeriod(uint256 _startTime, uint256 _endTime, uint256 _bonus); event Finalized(); event PresaleFallBack(uint256 _presaleWeiRaised); event PushInvestorList(address _investor); event RefundAll(uint256 _numToRefund); event ClaimedTokens(address _claimToken, address owner, uint256 balance); event Initialize(); function initialize ( address _kyc, address _token, address _vault, address _presale, address _bountyAddress, address _partnersAddress, address _ATCReserveLocker, address _teamLocker, address _tokenController, uint256 _maxEtherCap, uint256 _minEtherCap, uint256 _baseRate, uint256[] _additionalBonusAmounts ) onlyOwner { require(!initialized); require(_kyc != 0x00 && _token != 0x00 && _vault != 0x00 && _presale != 0x00); require(_bountyAddress != 0x00 && _partnersAddress != 0x00); require(_ATCReserveLocker != 0x00 && _teamLocker != 0x00); require(_tokenController != 0x00); require(0 < _minEtherCap && _minEtherCap < _maxEtherCap); require(_baseRate > 0); require(_additionalBonusAmounts[0] > 0); for (uint i = 0; i < _additionalBonusAmounts.length - 1; i++) { require(_additionalBonusAmounts[i] < _additionalBonusAmounts[i + 1]); } kyc = KYC(_kyc); token = ATC(_token); vault = RefundVault(_vault); presale = _presale; bountyAddress = _bountyAddress; partnersAddress = _partnersAddress; ATCReserveLocker = _ATCReserveLocker; teamLocker = _teamLocker; ATCController = _tokenController; maxEtherCap = _maxEtherCap; minEtherCap = _minEtherCap; baseRate = _baseRate; additionalBonusAmounts = _additionalBonusAmounts; initialized = true; Initialize(); } function () public payable { buy(msg.sender); } function presaleFallBack(uint256 _presaleWeiRaised) public returns (bool) { require(!presaleFallBackCalled); require(msg.sender == presale); weiRaised = _presaleWeiRaised; presaleFallBackCalled = true; PresaleFallBack(_presaleWeiRaised); return true; } function buy(address beneficiary) public payable whenNotPaused { // check validity require(presaleFallBackCalled); require(beneficiary != 0x00); require(kyc.registeredAddress(beneficiary)); require(onSale()); require(validPurchase()); require(!isFinalized); // calculate eth amount uint256 weiAmount = msg.value; uint256 toFund; uint256 postWeiRaised = add(weiRaised, weiAmount); if (postWeiRaised > maxEtherCap) { toFund = sub(maxEtherCap, weiRaised); } else { toFund = weiAmount; } require(toFund > 0); require(weiAmount >= toFund); uint256 rate = calculateRate(toFund); uint256 tokens = mul(toFund, rate); uint256 toReturn = sub(weiAmount, toFund); pushInvestorList(msg.sender); weiRaised = add(weiRaised, toFund); beneficiaryFunded[beneficiary] = add(beneficiaryFunded[beneficiary], toFund); token.generateTokens(beneficiary, tokens); if (toReturn > 0) { msg.sender.transfer(toReturn); } forwardFunds(toFund); CrowdSaleTokenPurchase(msg.sender, beneficiary, toFund, tokens); } function pushInvestorList(address investor) internal { if (!inInvestorList[investor]) { inInvestorList[investor] = true; investorList.push(investor); PushInvestorList(investor); } } function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && !maxReached(); } function forwardFunds(uint256 toFund) internal { vault.deposit.value(toFund)(msg.sender); } /** * @dev Checks whether minEtherCap is reached * @return true if min ether cap is reaced */ function minReached() public view returns (bool) { return weiRaised >= minEtherCap; } /** * @dev Checks whether maxEtherCap is reached * @return true if max ether cap is reaced */ function maxReached() public view returns (bool) { return weiRaised == maxEtherCap; } function getPeriodBonus() public view returns (uint256) { bool nowOnSale; uint256 currentPeriod; for (uint i = 0; i < periods.length; i++) { if (periods[i].startTime <= now && now <= periods[i].endTime) { nowOnSale = true; currentPeriod = i; break; } } require(nowOnSale); return periods[currentPeriod].bonus; } /** * @dev rate = baseRate * (100 + bonus) / 100 */ function calculateRate(uint256 toFund) public view returns (uint256) { uint bonus = getPeriodBonus(); // bonus for eth amount if (additionalBonusAmounts[0] <= toFund) { bonus = add(bonus, 5); // 5% amount bonus for more than 300 ETH } if (additionalBonusAmounts[1] <= toFund) { bonus = add(bonus, 5); // 10% amount bonus for more than 6000 ETH } if (additionalBonusAmounts[2] <= toFund) { bonus = 25; // final 25% amount bonus for more than 8000 ETH } if (additionalBonusAmounts[3] <= toFund) { bonus = 30; // final 30% amount bonus for more than 10000 ETH } return div(mul(baseRate, add(bonus, 100)), 100); } function startPeriod(uint256 _startTime, uint256 _endTime) public onlyOwner returns (bool) { require(periods.length < MAX_PERIOD_COUNT); require(now < _startTime && _startTime < _endTime); if (periods.length != 0) { require(sub(_endTime, _startTime) <= 7 days); require(periods[periods.length - 1].endTime < _startTime); } // 15% -> 10% -> 5% -> 0% Period memory newPeriod; newPeriod.startTime = _startTime; newPeriod.endTime = _endTime; if(periods.length < 3) { newPeriod.bonus = sub(15, mul(5, periods.length)); } else { newPeriod.bonus = 0; } periods.push(newPeriod); StartPeriod(_startTime, _endTime, newPeriod.bonus); return true; } function onSale() public returns (bool) { bool nowOnSale; for (uint i = 0; i < periods.length; i++) { if (periods[i].startTime <= now && now <= periods[i].endTime) { nowOnSale = true; break; } } return nowOnSale; } /** * @dev should be called after crowdsale ends, to do */ function finalize() onlyOwner { require(!isFinalized); require(!onSale() || maxReached()); finalizedTime = now; finalization(); Finalized(); isFinalized = true; } /** * @dev end token minting on finalization, mint tokens for dev team and reserve wallets */ function finalization() internal { if (minReached()) { vault.close(); uint256 totalToken = token.totalSupply(); // token distribution : 50% for sale, 5% for bounty, 15% for partners, 15% for reserve, 15% for team uint256 bountyAmount = div(mul(totalToken, 5), 50); uint256 partnersAmount = div(mul(totalToken, 15), 50); uint256 reserveAmount = div(mul(totalToken, 15), 50); uint256 teamAmount = div(mul(totalToken, 15), 50); distributeToken(bountyAmount, partnersAmount, reserveAmount, teamAmount); token.enableTransfers(true); } else { vault.enableRefunds(); } token.finishGenerating(); token.changeController(ATCController); } function distributeToken(uint256 bountyAmount, uint256 partnersAmount, uint256 reserveAmount, uint256 teamAmount) internal { require(bountyAddress != 0x00 && partnersAddress != 0x00); require(ATCReserveLocker != 0x00 && teamLocker != 0x00); token.generateTokens(bountyAddress, bountyAmount); token.generateTokens(partnersAddress, partnersAmount); token.generateTokens(ATCReserveLocker, reserveAmount); token.generateTokens(teamLocker, teamAmount); } /** * @dev refund a lot of investors at a time checking onlyOwner * @param numToRefund uint256 The number of investors to refund */ function refundAll(uint256 numToRefund) onlyOwner { require(isFinalized); require(!minReached()); require(numToRefund > 0); uint256 limit = refundCompleted + numToRefund; if (limit > investorList.length) { limit = investorList.length; } for(uint256 i = refundCompleted; i < limit; i++) { vault.refund(investorList[i]); } refundCompleted = limit; RefundAll(numToRefund); } /** * @dev if crowdsale is unsuccessful, investors can claim refunds here * @param investor address The account to be refunded */ function claimRefund(address investor) returns (bool) { require(isFinalized); require(!minReached()); return vault.refund(investor); } function claimTokens(address _claimToken) public onlyOwner { if (token.controller() == address(this)) { token.claimTokens(_claimToken); } if (_claimToken == 0x0) { owner.transfer(this.balance); return; } ERC20Basic claimToken = ERC20Basic(_claimToken); uint256 balance = claimToken.balanceOf(this); claimToken.transfer(owner, balance); ClaimedTokens(_claimToken, owner, balance); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract ReserveLocker is SafeMath{ using SafeERC20 for ERC20Basic; ERC20Basic public token; ATCCrowdSale public crowdsale; address public beneficiary; function ReserveLocker(address _token, address _crowdsale, address _beneficiary) { require(_token != 0x00); require(_crowdsale != 0x00); require(_beneficiary != 0x00); token = ERC20Basic(_token); crowdsale = ATCCrowdSale(_crowdsale); beneficiary = _beneficiary; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { uint256 finalizedTime = crowdsale.finalizedTime(); require(finalizedTime > 0 && now > add(finalizedTime, 2 years)); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } function setToken(address newToken) public { require(msg.sender == beneficiary); require(newToken != 0x00); token = ERC20Basic(newToken); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TeamLocker is SafeMath{ using SafeERC20 for ERC20Basic; ERC20Basic public token; ATCCrowdSale public crowdsale; address[] public beneficiaries; uint256 public collectedTokens; function TeamLocker(address _token, address _crowdsale, address[] _beneficiaries) { require(_token != 0x00); require(_crowdsale != 0x00); for (uint i = 0; i < _beneficiaries.length; i++) { require(_beneficiaries[i] != 0x00); } token = ERC20Basic(_token); crowdsale = ATCCrowdSale(_crowdsale); beneficiaries = _beneficiaries; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { uint256 balance = token.balanceOf(address(this)); uint256 total = add(balance, collectedTokens); uint256 finalizedTime = crowdsale.finalizedTime(); require(finalizedTime > 0); uint256 lockTime1 = add(finalizedTime, 183 days); // 6 months uint256 lockTime2 = add(finalizedTime, 1 years); // 1 year uint256 currentRatio = 20; if (now >= lockTime1) { currentRatio = 50; } if (now >= lockTime2) { currentRatio = 100; } uint256 releasedAmount = div(mul(total, currentRatio), 100); uint256 grantAmount = sub(releasedAmount, collectedTokens); require(grantAmount > 0); collectedTokens = add(collectedTokens, grantAmount); uint256 grantAmountForEach = div(grantAmount, 3); for (uint i = 0; i < beneficiaries.length; i++) { token.safeTransfer(beneficiaries[i], grantAmountForEach); } } function setToken(address newToken) public { require(newToken != 0x00); bool isBeneficiary; for (uint i = 0; i < beneficiaries.length; i++) { if (msg.sender == beneficiaries[i]) { isBeneficiary = true; } } require(isBeneficiary); token = ERC20Basic(newToken); } }
/ ERC20 Methods/ Send `_amount` tokens to `_to` from `msg.sender` _to The address of the recipient _amount The amount of tokens to be transferred return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); }
2,528,757
// CdBy mand0mb3 // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol"; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import './ABDKMathQuad.sol'; import './Coin1.sol'; contract Swap{ address private owner; struct Account{ uint32 id; string name; bool received; //uint256 balance; } event TokensSwap( address account, uint id_from, uint id_to, uint amount, uint rate ); mapping(address=>Account) private proprietarios; mapping(address=>uint256) private max; mapping(address=>mapping(address=>uint256)) private rates; address[] private coins; address[] private students; uint256 private price = 1*(uint256(10)**18); uint256 constant fee = 10; modifier onlyOwner(){ require(msg.sender==owner, "Acesso restrito apenas para Admin!"); _; } modifier onlyReal(){ require(msg.sender!=address(0), "Endereco Invalido!"); _; } constructor(){ owner = msg.sender; } //OBS ADD EVENTS ON THE FUNCTIONS----------------> function signUp(uint32 id_, string memory name_) public onlyReal returns(bool){ require(proprietarios[msg.sender].id==0,"Conta existente"); for (uint256 index = 0; index < students.length; index++) { //if (proprietarios[students[index]].id == id_) return false; require(proprietarios[msg.sender].id!=id_,"Conta existente"); } /*for (uint256 index = 0; index < coins.length; index++) { ERC20 temp = ERC20(coins[index]); temp.approve(address(this),1000000*(uint256(10)**18)); }*/ students.push(msg.sender); proprietarios[msg.sender]=Account({id:id_, name:name_, received:false}); return true; } function donateCoin(address student, uint256 amount) public onlyOwner returns(bool){ require(proprietarios[student].received==false, "Conta ja doada"); for (uint256 index = 0; index < coins.length; index++) { ERC20 temp = ERC20(coins[index]); temp.transferFrom(owner,student,amount*(uint256(10)**18)); } proprietarios[student].received=true; return true; } function addCoin(address coin) public returns(bool){ require(keccak256(bytes(ERC20(coin).name()))!=keccak256(bytes("")), "Endereco da Coin Invalido"); for (uint256 index = 0; index < coins.length; index++) { if (coin == coins[index]) return false; /*for (uint256 index_ = index+1; index_ < coins.length; index_++) { initPar(coins[index],coins[index_]); }*/ } coins.push(coin); max[coin]=div(ERC20(coin).balanceOf(address(this)),10**ERC20(coin).decimals()); return true; } function priceCoin(address _coinFrom, address _coinTo) public view returns(uint256){ if (rates[_coinFrom][_coinTo]<=0) return 1*(uint256(10)**18); return div(rates[_coinFrom][_coinTo],fee);//price + price*(rates[_coinFrom][_coinTo]+div(max[_coinTo],uint256(10)**18)); } function priceCoinAt(uint index_1, uint index_2) public view returns(uint256){ require(index_1<getCoinsLength(),"Index Out of Range"); require(index_2<getCoinsLength(),"Index Out of Range"); if (rates[coins[index_1]][coins[index_2]]<=0) return 1*(uint256(10)**18); return div(rates[coins[index_1]][coins[index_2]],fee); } function getRate(address _coinFrom, address _coinTo) public view returns(uint256){ return rates[_coinFrom][_coinTo]; } function getMax(address _coinFrom) public view returns(uint256){ return max[_coinFrom]; } function getStudentsLength() public view returns(uint256){ return students.length; } function getCoinsLength() public view returns(uint256){ return coins.length; } function getStudent(uint256 index) public view returns(Account memory){ require(index<getStudentsLength(),"Index Out of Range"); return proprietarios[students[index]]; } function getCoinSymbol(uint256 index) public view returns(string memory){ require(index<getCoinsLength(),"Index Out of Range"); return ERC20(coins[index]).symbol(); } function approve(address _coinFrom, uint256 amount) public virtual returns(bool){ require(msg.sender!=address(this),"Invalid Operation"); ERC20 coinFrom_ = ERC20(_coinFrom); return coinFrom_.increaseAllowance(address(this), amount*(10**uint256(coinFrom_.decimals()))); } function balanceOf(address _coinFrom) public view onlyReal returns(uint256){ ERC20 coinFrom_ = ERC20(_coinFrom); return coinFrom_.balanceOf(msg.sender); } function balanceOfAt(uint256 index_U, uint256 index_C) public view onlyReal returns(uint256){ require(index_C<getCoinsLength(),"Index Out of Range"); require(index_U<getStudentsLength(),"Index Out of Range"); ERC20 coinFrom_ = ERC20(coins[index_C]); return coinFrom_.balanceOf(students[index_U]); } function swap(address _coinFrom, address _coinTo, uint256 amount) public returns(bool){ ERC20 coinFrom_ = ERC20(_coinFrom); ERC20 coinTo_ = ERC20(_coinTo); if (rates[_coinFrom][_coinTo]<=0) rates[_coinFrom][_coinTo]=1*(uint256(10)**18); uint256 temp_ = 100 + div(rates[_coinFrom][_coinTo],fee); require(amount>=temp_, "Valor insuficente para swap"); //uint256 temp_price = price + price*div(rates[_coinFrom][_coinTo]*100,div(max[_coinTo],uint256(10)**_coinTo.decimals())); //coinFrom_.approve(address(this), mul(amount,(uint256(10)**18))); coinFrom_.transferFrom(msg.sender, address(this), amount);//mul(amount,(uint256(10)**18))); sendCoin(msg.sender, coinTo_, div(amount,temp_)); //temp_ += div(/*mul(*/amount/*,(uint256(10)**18)) */,rates[_coinFrom][_coinTo]); rates[_coinFrom][_coinTo] += div(amount,temp_); if (rates[_coinTo][_coinFrom]> div(amount,temp_)) rates[_coinTo][_coinFrom] -= div(amount,temp_); return true; } function sendCoin(address target, ERC20 coinTo_, uint256 amount) internal virtual{ coinTo_.transfer(target, amount); } function initPar(address _coinFrom, address _coinTo) internal virtual{ if (rates[_coinFrom][_coinTo]<=0) rates[_coinFrom][_coinTo]=1*(uint256(10)**18); if (rates[_coinTo][_coinFrom]<=0) rates[_coinTo][_coinFrom]=1*(uint256(10)**18); } function div(uint256 x, uint256 y) public pure returns(uint256){ return ABDKMathQuad.toUInt( ABDKMathQuad.div(ABDKMathQuad.fromUInt(x),ABDKMathQuad.fromUInt(y)) ); } function mul(uint256 x, uint256 y) public pure returns(uint256){ return ABDKMathQuad.toUInt( ABDKMathQuad.mul(ABDKMathQuad.fromUInt(x),ABDKMathQuad.fromUInt(y)) ); } function value(uint256 a) public pure returns (uint256) { return mul(a ,(uint256(10)**10)); } } // Learn about automatic market to study formule to
uint256 temp_price = price + pricediv(rates[_coinFrom][_coinTo]100,div(max[_coinTo],uint256(10)_coinTo.decimals()));coinFrom_.approve(address(this), mul(amount,(uint256(10)18)));temp_ += div(/mul(/amount/,(uint256(10)18)) /,rates[_coinFrom][_coinTo]);
function swap(address _coinFrom, address _coinTo, uint256 amount) public returns(bool){ ERC20 coinFrom_ = ERC20(_coinFrom); ERC20 coinTo_ = ERC20(_coinTo); if (rates[_coinFrom][_coinTo]<=0) rates[_coinFrom][_coinTo]=1*(uint256(10)**18); uint256 temp_ = 100 + div(rates[_coinFrom][_coinTo],fee); require(amount>=temp_, "Valor insuficente para swap"); sendCoin(msg.sender, coinTo_, div(amount,temp_)); rates[_coinFrom][_coinTo] += div(amount,temp_); if (rates[_coinTo][_coinFrom]> div(amount,temp_)) rates[_coinTo][_coinFrom] -= div(amount,temp_); return true; }
14,049,400
./partial_match/1/0x70F2D63F43174Ed08AaDaA7C3Db9740C140Cf543/sources/GeneralizedTCR.sol
Change the base amount required as a deposit to challenge a removal request. _removalChallengeBaseDeposit The new base amount of wei required to challenge a removal request./
function changeRemovalChallengeBaseDeposit(uint _removalChallengeBaseDeposit) external onlyGovernor { removalChallengeBaseDeposit = _removalChallengeBaseDeposit; }
3,687,601
./partial_match/1/0xdbc61a1685C6F70c11cBb7da70338352b1Fa4d51/sources/DigiDaigakuGiantDragons.sol
Mints multiple Giant Dragons created with the specified Baby Dragon and Dragon Essence tokens. Throws if `to` address is zero address. Throws if the quantity is zero. Throws if the caller is not a whitelisted minter. Throws if minting would exceed the max supply. <h4>Postconditions:</h4> 1. `quantity` Giant Dragons have been minted to the specified `to` address, where `quantity` is the length of the token id arrays. 2. `quantity` DragonMinted events has been emitted, where `quantity` is the length of the token id arrays. to The address of the destination of the Giant Dragons. babyDragonTokenIds An array of Baby DragonTokenIds to be used to mint the Giant Dragons. dragonEssenceTokenIds An array of DragonEssenceTokenIds to be used to mint the Giant Dragons./
function mintDragonsBatch( address to, uint256[] calldata babyDragonTokenIds, uint256[] calldata dragonEssenceTokenIds ) external { _requireMinterIsWhitelisted(_msgSender()); unchecked { for (uint256 i = 0; i < dragonEssenceTokenIds.length; ++i) { _mint(to, babyDragonTokenIds[i]); emit GiantDragonMinted(to, babyDragonTokenIds[i], dragonEssenceTokenIds[i]); } } }
15,729,339
/** ██████ ███ ███ ██ ████████ ██ ████ ████ ██ ██ ██ ███ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██████ ██ ██ ███████ ██ */ // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract GoliathMountainLedgerToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; address private _marketingWalletAddress = 0xeE526d536119BFD3c26d689c090c85B02306A68d; // Owner Address uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Goliath Mountain Ledger Token"; string private _symbol = "GMLT"; uint8 private _decimals = 18; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _marketingFee = 1; uint256 private _previousmarketingFee = _marketingFee; uint256 public _liquidityFee = 0; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 100000000 * 10**18; uint256 private numTokensSellToAddToLiquidity = 100000000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[owner()] = _rTotal; //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);// BSC testnet //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);// BSC mainnet IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);// Ethereum mainnet for uniswap // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), owner(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } /** function _mktAddress() public view returns (address) { return _marketingWalletAddress; } */ function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takemarketing(tmarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setmarketingFeePercent(uint256 marketingFee) external onlyOwner() { _marketingFee = marketingFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tmarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tmarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tmarketing = calculatemarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tmarketing); return (tTransferAmount, tFee, tLiquidity, tmarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rmarketing = tmarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rmarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takemarketing(uint256 tmarketing) private { uint256 currentRate = _getRate(); uint256 rmarketing = tmarketing.mul(currentRate); _rOwned[_marketingWalletAddress] = _rOwned[_marketingWalletAddress].add(rmarketing); if(_isExcluded[_marketingWalletAddress]) _tOwned[_marketingWalletAddress] = _tOwned[_marketingWalletAddress].add(tmarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculatemarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousmarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _marketingFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousmarketingFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takemarketing(tmarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takemarketing(tmarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tmarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takemarketing(tmarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function ChangemarketingAddress(address chartadd) public onlyOwner { _marketingWalletAddress = chartadd; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal { } }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); ██████ ███ ███ ██ ████████ }
10,012,986
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract Time { /** * @dev Current time getter * @return Current time in seconds */ function _currentTime() internal view returns (uint256) { return block.timestamp; } } /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Lockable { // locked values specified by address mapping(address => uint256) public lockedValues; /** * @dev Method to lock specified value by specified address * @param _for Address for which the value will be locked * @param _value Value that be locked */ function _lock(address _for, uint256 _value) internal { require(_for != address(0) && _value > 0, "Invalid lock operation configuration."); if (_value != lockedValues[_for]) { lockedValues[_for] = _value; } } /** * @dev Method to unlock (reset) locked value * @param _for Address for which the value will be unlocked */ function _unlock(address _for) internal { require(_for != address(0), "Invalid unlock operation configuration."); if (lockedValues[_for] != 0) { lockedValues[_for] = 0; } } } contract Operable is Ownable, RBAC { // role key string public constant ROLE_OPERATOR = "operator"; /** * @dev Reverts in case account is not Owner or Operator role */ modifier hasOwnerOrOperatePermission() { require(msg.sender == owner || hasRole(msg.sender, ROLE_OPERATOR), "Access denied."); _; } /** * @dev Getter to determine if address is in whitelist */ function operator(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_OPERATOR); } /** * @dev Method to add accounts with Operator role * @param _operator Address that will receive Operator role access */ function addOperator(address _operator) public onlyOwner { addRole(_operator, ROLE_OPERATOR); } /** * @dev Method to remove accounts with Operator role * @param _operator Address that will loose Operator role access */ function removeOperator(address _operator) public onlyOwner { removeRole(_operator, ROLE_OPERATOR); } } contract Withdrawal is Ownable { // Address to which funds will be withdrawn address public withdrawWallet; /** * Event for withdraw logging * @param value Value that was withdrawn */ event WithdrawLog(uint256 value); /** * @param _withdrawWallet Address to which funds will be withdrawn */ constructor(address _withdrawWallet) public { require(_withdrawWallet != address(0), "Invalid funds holder wallet."); withdrawWallet = _withdrawWallet; } /** * @dev Transfers funds from the contract to the specified withdraw wallet address */ function withdrawAll() external onlyOwner { uint256 weiAmount = address(this).balance; withdrawWallet.transfer(weiAmount); emit WithdrawLog(weiAmount); } /** * @dev Transfers a part of the funds from the contract to the specified withdraw wallet address * @param _weiAmount Part of the funds to be withdrawn */ function withdraw(uint256 _weiAmount) external onlyOwner { require(_weiAmount <= address(this).balance, "Not enough funds."); withdrawWallet.transfer(_weiAmount); emit WithdrawLog(_weiAmount); } } contract PriceStrategy is Time, Operable { using SafeMath for uint256; /** * Describes stage parameters * @param start Stage start date * @param end Stage end date * @param volume Number of tokens available for the stage * @param priceInCHF Token price in CHF for the stage * @param minBonusVolume The minimum number of tokens after which the bonus tokens is added * @param bonus Percentage of bonus tokens */ struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; } /** * Describes lockup period parameters * @param periodInSec Lockup period in seconds * @param bonus Lockup bonus tokens percentage */ struct LockupPeriod { uint256 expires; uint256 bonus; } // describes stages available for ICO lifetime Stage[] public stages; // lockup periods specified by the period in month mapping(uint256 => LockupPeriod) public lockupPeriods; // number of decimals supported by CHF rates uint256 public constant decimalsCHF = 18; // minimum allowed investment in CHF (decimals 1e+18) uint256 public minInvestmentInCHF; // ETH rate in CHF uint256 public rateETHtoCHF; /** * Event for ETH to CHF rate changes logging * @param newRate New rate value */ event RateChangedLog(uint256 newRate); /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF) public { require(_minInvestmentInCHF > 0, "Minimum investment can not be set to 0."); minInvestmentInCHF = _minInvestmentInCHF; setETHtoCHFrate(_rateETHtoCHF); // PRE-ICO stages.push(Stage({ start: 1536969600, // 15th Sep, 2018 00:00:00 end: 1542239999, // 14th Nov, 2018 23:59:59 volume: uint256(25000000000).mul(10 ** 18), // (twenty five billion) priceInCHF: uint256(2).mul(10 ** 14), // CHF 0.00020 minBonusVolume: 0, bonus: 0, lock: false })); // ICO stages.push(Stage({ start: 1542240000, // 15th Nov, 2018 00:00:00 end: 1550188799, // 14th Feb, 2019 23:59:59 volume: uint256(65000000000).mul(10 ** 18), // (forty billion) priceInCHF: uint256(4).mul(10 ** 14), // CHF 0.00040 minBonusVolume: uint256(400000000).mul(10 ** 18), // (four hundred million) bonus: 2000, // 20% bonus tokens lock: true })); _setLockupPeriod(1550188799, 18, 3000); // 18 months after the end of the ICO / 30% _setLockupPeriod(1550188799, 12, 2000); // 12 months after the end of the ICO / 20% _setLockupPeriod(1550188799, 6, 1000); // 6 months after the end of the ICO / 10% } /** * @dev Updates ETH to CHF rate * @param _rateETHtoCHF Cost of ETH in CHF */ function setETHtoCHFrate(uint256 _rateETHtoCHF) public hasOwnerOrOperatePermission { require(_rateETHtoCHF > 0, "Rate can not be set to 0."); rateETHtoCHF = _rateETHtoCHF; emit RateChangedLog(rateETHtoCHF); } /** * @dev Tokens amount based on investment value in wei * @param _wei Investment value in wei * @param _lockup Lockup period in months * @param _sold Number of tokens sold by the moment * @return Amount of tokens and bonuses */ function getTokensAmount(uint256 _wei, uint256 _lockup, uint256 _sold) public view returns (uint256 tokens, uint256 bonus) { uint256 chfAmount = _wei.mul(rateETHtoCHF).div(10 ** decimalsCHF); require(chfAmount >= minInvestmentInCHF, "Investment value is below allowed minimum."); Stage memory currentStage = _getCurrentStage(); require(currentStage.priceInCHF > 0, "Invalid price value."); tokens = chfAmount.mul(10 ** decimalsCHF).div(currentStage.priceInCHF); uint256 bonusSize; if (tokens >= currentStage.minBonusVolume) { bonusSize = currentStage.bonus.add(lockupPeriods[_lockup].bonus); } else { bonusSize = lockupPeriods[_lockup].bonus; } bonus = tokens.mul(bonusSize).div(10 ** 4); uint256 total = tokens.add(bonus); require(currentStage.volume > _sold.add(total), "Not enough tokens available."); } /** * @dev Finds current stage parameters according to the rules and current date and time * @return Current stage parameters (available volume of tokens and price in CHF) */ function _getCurrentStage() internal view returns (Stage) { uint256 index = 0; uint256 time = _currentTime(); Stage memory result; while (index < stages.length) { Stage memory stage = stages[index]; if ((time >= stage.start && time <= stage.end)) { result = stage; break; } index++; } return result; } /** * @dev Sets bonus for specified lockup period. Allowed only for contract owner * @param _startPoint Lock start point (is seconds) * @param _period Lockup period (in months) * @param _bonus Percentage of bonus tokens */ function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private { uint256 expires = _startPoint.add(_period.mul(2628000)); lockupPeriods[_period] = LockupPeriod({ expires: expires, bonus: _bonus }); } } contract BaseCrowdsale { using SafeMath for uint256; using SafeERC20 for CosquareToken; // The token being sold CosquareToken public token; // Total amount of tokens sold uint256 public tokensSold; /** * @dev Event for tokens purchase logging * @param purchaseType Who paid for the tokens * @param beneficiary Who got the tokens * @param value Value paid for purchase * @param tokens Amount of tokens purchased * @param bonuses Amount of bonuses received */ event TokensPurchaseLog(string purchaseType, address indexed beneficiary, uint256 value, uint256 tokens, uint256 bonuses); /** * @param _token Address of the token being sold */ constructor(CosquareToken _token) public { require(_token != address(0), "Invalid token address."); token = _token; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { require(msg.data.length == 0, "Should not accept data."); _buyTokens(msg.sender, msg.value, "ETH"); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) external payable { _buyTokens(_beneficiary, msg.value, "ETH"); } /** * @dev Tokens purchase for wei investments * @param _beneficiary Address performing the token purchase * @param _amount Amount of tokens purchased * @param _investmentType Investment channel string */ function _buyTokens(address _beneficiary, uint256 _amount, string _investmentType) internal { _preValidatePurchase(_beneficiary, _amount); (uint256 tokensAmount, uint256 tokenBonus) = _getTokensAmount(_beneficiary, _amount); uint256 totalAmount = tokensAmount.add(tokenBonus); _processPurchase(_beneficiary, totalAmount); emit TokensPurchaseLog(_investmentType, _beneficiary, _amount, tokensAmount, tokenBonus); _postPurchaseUpdate(_beneficiary, totalAmount); } /** * @dev Validation of an executed purchase * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0), "Invalid beneficiary address."); require(_weiAmount > 0, "Invalid investment value."); } /** * @dev Abstract function to count the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus); /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { _deliverTokens(_beneficiary, _tokensAmount); } /** * @dev Deliver tokens to investor * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _deliverTokens(address _beneficiary, uint256 _tokensAmount) internal { token.safeTransfer(_beneficiary, _tokensAmount); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { tokensSold = tokensSold.add(_tokensAmount); } } contract LockableCrowdsale is Time, Lockable, Operable, PriceStrategy, BaseCrowdsale { using SafeMath for uint256; /** * @dev Locks the next purchase for the provision of bonus tokens * @param _beneficiary Address for which the next purchase will be locked * @param _lockupPeriod The period to which tokens will be locked from the next purchase */ function lockNextPurchase(address _beneficiary, uint256 _lockupPeriod) external hasOwnerOrOperatePermission { require(_lockupPeriod == 6 || _lockupPeriod == 12 || _lockupPeriod == 18, "Invalid lock interval"); Stage memory currentStage = _getCurrentStage(); require(currentStage.lock, "Lock operation is not allowed."); _lock(_beneficiary, _lockupPeriod); } /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { super._processPurchase(_beneficiary, _tokensAmount); uint256 lockedValue = lockedValues[_beneficiary]; if (lockedValue > 0) { uint256 expires = lockupPeriods[lockedValue].expires; token.lock(_beneficiary, _tokensAmount, expires); } } /** * @dev Counts the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus) { (tokens, bonus) = getTokensAmount(_weiAmount, lockedValues[_beneficiary], tokensSold); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { super._postPurchaseUpdate(_beneficiary, _tokensAmount); _unlock(_beneficiary); } } contract Whitelist is RBAC, Operable { // role key string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator Operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev Add an address to the whitelist * @param _operator Operator address */ function addAddressToWhitelist(address _operator) public hasOwnerOrOperatePermission { addRole(_operator, ROLE_WHITELISTED); } /** * @dev Getter to determine if address is in whitelist * @param _operator The address to be added to the whitelist * @return True if the address is in the whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev Add addresses to the whitelist * @param _operators Operators addresses */ function addAddressesToWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev Remove an address from the whitelist * @param _operator Operator address */ function removeAddressFromWhitelist(address _operator) public hasOwnerOrOperatePermission { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev Remove addresses from the whitelist * @param _operators Operators addresses */ function removeAddressesFromWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract WhitelistedCrowdsale is Whitelist, BaseCrowdsale { /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyIfWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PausableCrowdsale is Pausable, BaseCrowdsale { /** * @dev Extend parent behavior requiring contract not to be paused * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract CosquareToken is Time, StandardToken, DetailedERC20, Ownable { using SafeMath for uint256; /** * Describes locked balance * @param expires Time when tokens will be unlocked * @param value Amount of the tokens is locked */ struct LockedBalance { uint256 expires; uint256 value; } // locked balances specified be the address mapping(address => LockedBalance[]) public lockedBalances; // sale wallet (65%) address public saleWallet; // reserve wallet (15%) address public reserveWallet; // team wallet (15%) address public teamWallet; // strategic wallet (5%) address public strategicWallet; // end point, after which all tokens will be unlocked uint256 public lockEndpoint; /** * Event for lock logging * @param who The address on which part of the tokens is locked * @param value Amount of the tokens is locked * @param expires Time when tokens will be unlocked */ event LockLog(address indexed who, uint256 value, uint256 expires); /** * @param _saleWallet Sale wallet * @param _reserveWallet Reserve wallet * @param _teamWallet Team wallet * @param _strategicWallet Strategic wallet * @param _lockEndpoint End point, after which all tokens will be unlocked */ constructor(address _saleWallet, address _reserveWallet, address _teamWallet, address _strategicWallet, uint256 _lockEndpoint) DetailedERC20("cosquare", "CSQ", 18) public { require(_lockEndpoint > 0, "Invalid global lock end date."); lockEndpoint = _lockEndpoint; _configureWallet(_saleWallet, 65000000000000000000000000000); // 6.5e+28 saleWallet = _saleWallet; _configureWallet(_reserveWallet, 15000000000000000000000000000); // 1.5e+28 reserveWallet = _reserveWallet; _configureWallet(_teamWallet, 15000000000000000000000000000); // 1.5e+28 teamWallet = _teamWallet; _configureWallet(_strategicWallet, 5000000000000000000000000000); // 0.5e+28 strategicWallet = _strategicWallet; } /** * @dev Setting the initial value of the tokens to the wallet * @param _wallet Address to be set up * @param _amount The number of tokens to be assigned to this address */ function _configureWallet(address _wallet, uint256 _amount) private { require(_wallet != address(0), "Invalid wallet address."); totalSupply_ = totalSupply_.add(_amount); balances[_wallet] = _amount; emit Transfer(address(0), _wallet, _amount); } /** * @dev Throws if the address does not have enough not locked balance * @param _who The address to transfer from * @param _value The amount to be transferred */ modifier notLocked(address _who, uint256 _value) { uint256 time = _currentTime(); if (lockEndpoint > time) { uint256 index = 0; uint256 locked = 0; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires > time) { locked = locked.add(lockedBalances[_who][index].value); } index++; } require(_value <= balances[_who].sub(locked), "Not enough unlocked tokens"); } _; } /** * @dev Overridden to check whether enough not locked balance * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public notLocked(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Overridden to check whether enough not locked balance * @param _to The address to transfer to * @param _value The amount to be transferred */ function transfer(address _to, uint256 _value) public notLocked(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Gets the locked balance of the specified address * @param _owner The address to query the locked balance of * @param _expires Time of expiration of the lock (If equals to 0 - returns all locked tokens at this moment) * @return An uint256 representing the amount of locked balance by the passed address */ function lockedBalanceOf(address _owner, uint256 _expires) external view returns (uint256) { uint256 time = _currentTime(); uint256 index = 0; uint256 locked = 0; if (lockEndpoint > time) { while (index < lockedBalances[_owner].length) { if (_expires > 0) { if (lockedBalances[_owner][index].expires == _expires) { locked = locked.add(lockedBalances[_owner][index].value); } } else { if (lockedBalances[_owner][index].expires >= time) { locked = locked.add(lockedBalances[_owner][index].value); } } index++; } } return locked; } /** * @dev Locks part of the balance for the specified address and for a certain period (3 periods expected) * @param _who The address of which will be locked part of the balance * @param _value The amount of tokens to be locked * @param _expires Time of expiration of the lock */ function lock(address _who, uint256 _value, uint256 _expires) public onlyOwner { uint256 time = _currentTime(); require(_who != address(0) && _value <= balances[_who] && _expires > time, "Invalid lock configuration."); uint256 index = 0; bool exist = false; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires == _expires) { exist = true; break; } index++; } if (exist) { lockedBalances[_who][index].value = lockedBalances[_who][index].value.add(_value); } else { lockedBalances[_who].push(LockedBalance({ expires: _expires, value: _value })); } emit LockLog(_who, _value, _expires); } } contract Crowdsale is Lockable, Operable, Withdrawal, PriceStrategy, LockableCrowdsale, WhitelistedCrowdsale, PausableCrowdsale { using SafeMath for uint256; /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF * @param _withdrawWallet Address to which funds will be withdrawn * @param _token Address of the token being sold */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF, address _withdrawWallet, CosquareToken _token) PriceStrategy(_rateETHtoCHF, _minInvestmentInCHF) Withdrawal(_withdrawWallet) BaseCrowdsale(_token) public { } /** * @dev Distributes tokens for wei investments * @param _beneficiary Address performing the token purchase * @param _ethAmount Investment value in ETH * @param _type Type of investment channel */ function distributeTokensForInvestment(address _beneficiary, uint256 _ethAmount, string _type) public hasOwnerOrOperatePermission { _buyTokens(_beneficiary, _ethAmount, _type); } /** * @dev Distributes tokens manually * @param _beneficiary Address performing the tokens distribution * @param _tokensAmount Amount of tokens distribution */ function distributeTokensManual(address _beneficiary, uint256 _tokensAmount) external hasOwnerOrOperatePermission { _preValidatePurchase(_beneficiary, _tokensAmount); _deliverTokens(_beneficiary, _tokensAmount); emit TokensPurchaseLog("MANUAL", _beneficiary, 0, _tokensAmount, 0); _postPurchaseUpdate(_beneficiary, _tokensAmount); } }
Extend parent behavior requiring beneficiary to be in whitelist. _beneficiary Token beneficiary _weiAmount Amount of wei contributed/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyIfWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); }
2,492,474
./full_match/80001/0x63F19192492859e5AC6A531B6CF1397454E16074/sources/Pearlium.sol
Sets the value of the `decimals`. This value is immutable, it can only be set once during construction./
function _beforeTokenTransfer( address from, address to, uint256 amount } constructor(uint8 decimals_) { _decimals = decimals_; }
847,118
//Address: 0xc654ec1fc5a1c76a19bf169ef2765cef23cdd236 //Contract name: PreIco //Balance: 0 Ether //Verification Date: 1/25/2018 //Transacion Count: 17 // CODE STARTS HERE pragma solidity ^0.4.18; contract AbstractToken { // This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions function totalSupply() public constant returns (uint256) {} function balanceOf(address owner) public constant returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public constant returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Issuance(address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { function mul(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) constant internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) { return div(mul(number, numerator), denominator); } } contract PreIco is SafeMath { /* * PreIco meta data */ string public constant name = "Remechain Presale Token"; string public constant symbol = "iRMC"; uint public constant decimals = 18; // addresses of managers address public manager; address public reserveManager; // addresses of escrows address public escrow; address public reserveEscrow; // BASE = 10^18 uint constant BASE = 1000000000000000000; // amount of supplied tokens uint public tokensSupplied = 0; // amount of supplied bounty reward uint public bountySupplied = 0; // Soft capacity = 6250 ETH uint public constant SOFT_CAPACITY = 2000000 * BASE; // Hard capacity = 18750 ETH uint public constant TOKENS_SUPPLY = 6000000 * BASE; // Amount of bounty reward uint public constant BOUNTY_SUPPLY = 350000 * BASE; // Total supply uint public constant totalSupply = TOKENS_SUPPLY + BOUNTY_SUPPLY; // 1 RMC = 0.003125 ETH for 600 000 000 RMC uint public constant TOKEN_PRICE = 3125000000000000; uint tokenAmount1 = 6000000 * BASE; uint tokenPriceMultiply1 = 1; uint tokenPriceDivide1 = 1; uint[] public tokenPriceMultiplies; uint[] public tokenPriceDivides; uint[] public tokenAmounts; // ETH balances of accounts mapping(address => uint) public ethBalances; uint[] public prices; uint[] public amounts; mapping(address => uint) private balances; // 2018.02.25 17:00 MSK uint public constant defaultDeadline = 1519567200; uint public deadline = defaultDeadline; // Is ICO frozen bool public isIcoStopped = false; // Addresses of allowed tokens for buying address[] public allowedTokens; // Amount of token mapping(address => uint) public tokenAmount; // Price of current token amount mapping(address => uint) public tokenPrice; // Full users list address[] public usersList; mapping(address => bool) isUserInList; // Number of users that have returned their money uint numberOfUsersReturned = 0; // user => token[] mapping(address => address[]) public userTokens; // user => token => amount mapping(address => mapping(address => uint)) public userTokensValues; /* * Events */ event BuyTokens(address indexed _user, uint _ethValue, uint _boughtTokens); event BuyTokensWithTokens(address indexed _user, address indexed _token, uint _tokenValue, uint _boughtTokens); event GiveReward(address indexed _to, uint _value); event IcoStoppedManually(); event IcoRunnedManually(); event WithdrawEther(address indexed _escrow, uint _ethValue); event WithdrawToken(address indexed _escrow, address indexed _token, uint _value); event ReturnEthersFor(address indexed _user, uint _value); event ReturnTokensFor(address indexed _user, address indexed _token, uint _value); event AddToken(address indexed _token, uint _amount, uint _price); event RemoveToken(address indexed _token); event MoveTokens(address indexed _from, address indexed _to, uint _value); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); /* * Modifiers */ modifier onlyManager { assert(msg.sender == manager || msg.sender == reserveManager); _; } modifier onlyManagerOrContract { assert(msg.sender == manager || msg.sender == reserveManager || msg.sender == address(this)); _; } modifier IcoIsActive { assert(isIcoActive()); _; } /// @dev Constructor of PreIco. /// @param _manager Address of manager /// @param _reserveManager Address of reserve manager /// @param _escrow Address of escrow /// @param _reserveEscrow Address of reserve escrow /// @param _deadline ICO deadline timestamp. If is 0, sets 1515679200 function PreIco(address _manager, address _reserveManager, address _escrow, address _reserveEscrow, uint _deadline) public { assert(_manager != 0x0); assert(_reserveManager != 0x0); assert(_escrow != 0x0); assert(_reserveEscrow != 0x0); manager = _manager; reserveManager = _reserveManager; escrow = _escrow; reserveEscrow = _reserveEscrow; if (_deadline != 0) { deadline = _deadline; } tokenPriceMultiplies.push(tokenPriceMultiply1); tokenPriceDivides.push(tokenPriceDivide1); tokenAmounts.push(tokenAmount1); } /// @dev Returns token balance of user. 1 token = 1/10^18 RMC /// @param _user Address of user function balanceOf(address _user) public returns(uint balance) { return balances[_user]; } /// @dev Returns, is ICO enabled function isIcoActive() public returns(bool isActive) { return !isIcoStopped && now < deadline; } /// @dev Returns, is SoftCap reached function isIcoSuccessful() public returns(bool isSuccessful) { return tokensSupplied >= SOFT_CAPACITY; } /// @dev Calculates number of tokens RMC for buying with custom price of token /// @param _amountOfToken Amount of RMC token /// @param _priceAmountOfToken Price of amount of RMC /// @param _value Amount of custom token function getTokensAmount(uint _amountOfToken, uint _priceAmountOfToken, uint _value) private returns(uint tokensToBuy) { uint currentStep; uint tokensRemoved = tokensSupplied; for (currentStep = 0; currentStep < tokenAmounts.length; currentStep++) { if (tokensRemoved >= tokenAmounts[currentStep]) { tokensRemoved -= tokenAmounts[currentStep]; } else { break; } } assert(currentStep < tokenAmounts.length); uint result = 0; for (; currentStep <= tokenAmounts.length; currentStep++) { assert(currentStep < tokenAmounts.length); uint tokenOnStepLeft = tokenAmounts[currentStep] - tokensRemoved; tokensRemoved = 0; uint howManyTokensCanBuy = _value * _amountOfToken / _priceAmountOfToken * tokenPriceDivides[currentStep] / tokenPriceMultiplies[currentStep]; if (howManyTokensCanBuy > tokenOnStepLeft) { result = add(result, tokenOnStepLeft); uint spent = tokenOnStepLeft * _priceAmountOfToken / _amountOfToken * tokenPriceMultiplies[currentStep] / tokenPriceDivides[currentStep]; if (_value <= spent) { break; } _value -= spent; tokensRemoved = 0; } else { result = add(result, howManyTokensCanBuy); break; } } return result; } /// @dev Calculates number of tokens RMC for buying with ETH /// @param _value Amount of ETH token function getTokensAmountWithEth(uint _value) private returns(uint tokensToBuy) { return getTokensAmount(BASE, TOKEN_PRICE, _value); } /// @dev Calculates number of tokens RMC for buying with ERC-20 token /// @param _token Address of ERC-20 token /// @param _tokenValue Amount of ETH token function getTokensAmountByTokens(address _token, uint _tokenValue) private returns(uint tokensToBuy) { assert(tokenPrice[_token] > 0); return getTokensAmount(tokenPrice[_token], tokenAmount[_token], _tokenValue); } /// @dev Solds tokens for user by ETH /// @param _user Address of user which buys token /// @param _value Amount of ETH. 1 _value = 1/10^18 ETH function buyTokens(address _user, uint _value) private IcoIsActive { uint boughtTokens = getTokensAmountWithEth(_value); burnTokens(boughtTokens); balances[_user] = add(balances[_user], boughtTokens); addUserToList(_user); BuyTokens(_user, _value, boughtTokens); } /// @dev Makes ERC-20 token sellable /// @param _token Address of ERC-20 token /// @param _amount Amount of current token /// @param _price Price of _amount of token function addToken(address _token, uint _amount, uint _price) onlyManager public { assert(_token != 0x0); assert(_amount > 0); assert(_price > 0); bool isNewToken = true; for (uint i = 0; i < allowedTokens.length; i++) { if (allowedTokens[i] == _token) { isNewToken = false; break; } } if (isNewToken) { allowedTokens.push(_token); } tokenPrice[_token] = _price; tokenAmount[_token] = _amount; } /// @dev Makes ERC-20 token not sellable /// @param _token Address of ERC-20 token function removeToken(address _token) onlyManager public { for (uint i = 0; i < allowedTokens.length; i++) { if (_token == allowedTokens[i]) { if (i < allowedTokens.length - 1) { allowedTokens[i] = allowedTokens[allowedTokens.length - 1]; } allowedTokens[allowedTokens.length - 1] = 0x0; allowedTokens.length--; break; } } tokenPrice[_token] = 0; tokenAmount[_token] = 0; } /// @dev add user to usersList /// @param _user Address of user function addUserToList(address _user) private { if (!isUserInList[_user]) { isUserInList[_user] = true; usersList.push(_user); } } /// @dev Makes amount of tokens not purchasable /// @param _amount Amount of RMC tokens function burnTokens(uint _amount) private { assert(add(tokensSupplied, _amount) <= TOKENS_SUPPLY); tokensSupplied = add(tokensSupplied, _amount); } /// @dev Takes ERC-20 tokens approved by user for using and gives him RMC tokens /// @param _token Address of ERC-20 token function buyWithTokens(address _token) public { buyWithTokensBy(msg.sender, _token); } /// @dev Takes ERC-20 tokens approved by user for using and gives him RMC tokens. Can be called by anyone /// @param _user Address of user /// @param _token Address of ERC-20 token function buyWithTokensBy(address _user, address _token) public IcoIsActive { // Checks whether the token is allowed assert(tokenPrice[_token] > 0); AbstractToken token = AbstractToken(_token); uint tokensToSend = token.allowance(_user, address(this)); assert(tokensToSend > 0); uint boughtTokens = getTokensAmountByTokens(_token, tokensToSend); burnTokens(boughtTokens); balances[_user] = add(balances[_user], boughtTokens); uint prevBalance = token.balanceOf(address(this)); assert(token.transferFrom(_user, address(this), tokensToSend)); assert(token.balanceOf(address(this)) - prevBalance == tokensToSend); userTokensValues[_user][_token] = add(userTokensValues[_user][_token], tokensToSend); addTokenToUser(_user, _token); addUserToList(_user); BuyTokensWithTokens(_user, _token, tokensToSend, boughtTokens); } /// @dev Makes amount of tokens returnable for user. If _buyTokens equals true, buy tokens /// @param _user Address of user /// @param _token Address of ERC-20 token /// @param _tokenValue Amount of ERC-20 token /// @param _buyTokens If true, buys tokens for this sum function addTokensToReturn(address _user, address _token, uint _tokenValue, bool _buyTokens) public onlyManager { // Checks whether the token is allowed assert(tokenPrice[_token] > 0); if (_buyTokens) { uint boughtTokens = getTokensAmountByTokens(_token, _tokenValue); burnTokens(boughtTokens); balances[_user] = add(balances[_user], boughtTokens); BuyTokensWithTokens(_user, _token, _tokenValue, boughtTokens); } userTokensValues[_user][_token] = add(userTokensValues[_user][_token], _tokenValue); addTokenToUser(_user, _token); addUserToList(_user); } /// @dev Adds ERC-20 tokens to user's token list /// @param _user Address of user /// @param _token Address of ERC-20 token function addTokenToUser(address _user, address _token) private { for (uint i = 0; i < userTokens[_user].length; i++) { if (userTokens[_user][i] == _token) { return; } } userTokens[_user].push(_token); } /// @dev Returns ether and tokens to user. Can be called only if ICO is ended and SoftCap is not reached function returnFunds() public { assert(!isIcoSuccessful() && !isIcoActive()); returnFundsFor(msg.sender); } /// @dev Moves tokens from one user to another. Can be called only by manager. This function added for users that send ether by stock exchanges function moveIcoTokens(address _from, address _to, uint _value) public onlyManager { balances[_from] = sub(balances[_from], _value); balances[_to] = add(balances[_to], _value); MoveTokens(_from, _to, _value); } /// @dev Returns ether and tokens to user. Can be called only by manager or contract /// @param _user Address of user function returnFundsFor(address _user) public onlyManagerOrContract returns(bool) { if (ethBalances[_user] > 0) { if (_user.send(ethBalances[_user])) { ReturnEthersFor(_user, ethBalances[_user]); ethBalances[_user] = 0; } } for (uint i = 0; i < userTokens[_user].length; i++) { address tokenAddress = userTokens[_user][i]; uint userTokenValue = userTokensValues[_user][tokenAddress]; if (userTokenValue > 0) { AbstractToken token = AbstractToken(tokenAddress); if (token.transfer(_user, userTokenValue)) { ReturnTokensFor(_user, tokenAddress, userTokenValue); userTokensValues[_user][tokenAddress] = 0; } } } balances[_user] = 0; } /// @dev Returns ether and tokens to list of users. Can be called only by manager /// @param _users Array of addresses of users function returnFundsForMultiple(address[] _users) public onlyManager { for (uint i = 0; i < _users.length; i++) { returnFundsFor(_users[i]); } } /// @dev Returns ether and tokens to 50 users. Can be called only by manager function returnFundsForAll() public onlyManager { assert(!isIcoActive() && !isIcoSuccessful()); uint first = numberOfUsersReturned; uint last = (first + 50 < usersList.length) ? first + 50 : usersList.length; for (uint i = first; i < last; i++) { returnFundsFor(usersList[i]); } numberOfUsersReturned = last; } /// @dev Withdraws ether and tokens to _escrow if SoftCap is reached /// @param _escrow Address of escrow function withdrawEtherTo(address _escrow) private { assert(isIcoSuccessful()); if (this.balance > 0) { if (_escrow.send(this.balance)) { WithdrawEther(_escrow, this.balance); } } for (uint i = 0; i < allowedTokens.length; i++) { AbstractToken token = AbstractToken(allowedTokens[i]); uint tokenBalance = token.balanceOf(address(this)); if (tokenBalance > 0) { if (token.transfer(_escrow, tokenBalance)) { WithdrawToken(_escrow, address(token), tokenBalance); } } } } /// @dev Withdraw ether and tokens to escrow. Can be called only by manager function withdrawEther() public onlyManager { withdrawEtherTo(escrow); } /// @dev Withdraw ether and tokens to reserve escrow. Can be called only by manager function withdrawEtherToReserveEscrow() public onlyManager { withdrawEtherTo(reserveEscrow); } /// @dev Enables disabled ICO. Can be called only by manager function runIco() public onlyManager { assert(isIcoStopped); isIcoStopped = false; IcoRunnedManually(); } /// @dev Disables ICO. Can be called only by manager function stopIco() public onlyManager { isIcoStopped = true; IcoStoppedManually(); } /// @dev Fallback function. Buy RMC tokens on sending ether function () public payable { buyTokens(msg.sender, msg.value); } /// @dev Gives bounty reward to user. Can be called only by manager /// @param _to Address of user /// @param _amount Amount of bounty function giveReward(address _to, uint _amount) public onlyManager { assert(_to != 0x0); assert(_amount > 0); assert(add(bountySupplied, _amount) <= BOUNTY_SUPPLY); bountySupplied = add(bountySupplied, _amount); balances[_to] = add(balances[_to], _amount); GiveReward(_to, _amount); } /// Adds other ERC-20 functions function transfer(address _to, uint _value) public returns (bool success) { return false; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { return false; } function approve(address _spender, uint _value) public returns (bool success) { return false; } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return 0; } }
Returns, is ICO enabled
function isIcoActive() public returns(bool isActive) { return !isIcoStopped && now < deadline; }
5,460,101
./full_match/28/0xD0Ce0c33E9AD6f1Db1B9b73f39Bf7A4dfA7c47C2/sources/contracts/comptroller/Comptroller.sol
Checks if the account should be allowed to borrow the underlying asset of the given market mToken The market to verify the borrow against borrower The account which would borrow the asset borrowAmount The amount of underlying the account would borrow return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Pausing is a very serious situation - we revert to sound the alarms only mTokens may call borrowAllowed if borrower not in market attempt to add borrower to the market Borrow cap of 0 corresponds to unlimited borrowing
function borrowAllowed( address mToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { require(msg.sender == mToken, "sender must be mToken"); Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[mToken]; if (borrowCap != 0) { uint256 totalBorrows = MToken(mToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, MToken(mToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } updateRewardBorrowIndex(mToken, borrowIndex); distributeBorrowerReward(mToken, borrower, borrowIndex); return uint256(Error.NO_ERROR); }
16,365,391