file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.4.24; 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) { // 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; } } // source : https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md contract ERC20 { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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 QuickxToken is ERC20 { using SafeMath for uint; // ------------------------------------------------------------------------ // EVENTS // ------------------------------------------------------------------------ event LogBurn(address indexed from, uint256 amount); event LogFreezed(address targetAddress, bool frozen); event LogEmerygencyFreezed(bool emergencyFreezeStatus); // ------------------------------------------------------------------------ // STATE VARIABLES // ------------------------------------------------------------------------ string public name = "QuickX Protocol"; string public symbol = "QCX"; uint8 public decimals = 8; address public owner; uint public totalSupply = 500000000 * (10 ** 8); uint public currentSupply = 250000000 * (10 ** 8); // 50% of total supply bool public emergencyFreeze = true; // ------------------------------------------------------------------------ // MAPPINNGS // ------------------------------------------------------------------------ mapping (address => uint) internal balances; mapping (address => mapping (address => uint) ) private allowed; mapping (address => bool) private frozen; // ------------------------------------------------------------------------ // CONSTRUCTOR // ------------------------------------------------------------------------ constructor () public { owner = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); } // ------------------------------------------------------------------------ // MODIFIERS // ------------------------------------------------------------------------ modifier onlyOwner { require(msg.sender == owner); _; } modifier unfreezed(address _account) { require(!frozen[_account]); _; } modifier noEmergencyFreeze() { require(!emergencyFreeze); _; } // ------------------------------------------------------------------------ // Transfer Token // ------------------------------------------------------------------------ function transfer(address _to, uint _value) public unfreezed(_to) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { require(_to != 0x0); _transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Approve others to spend on your behalf // RACE CONDITION HANDLED // ------------------------------------------------------------------------ function approve(address _spender, uint _value) public unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { // 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((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() 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 unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { uint oldAllowance = allowed[msg.sender][_spender]; if (_subtractedValue > oldAllowance) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldAllowance.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Transferred approved amount from other's account // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _value) public unfreezed(_to) unfreezed(_from) noEmergencyFreeze() returns (bool success) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } // ------------------------------------------------------------------------ // ONLYOWNER METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Freeze account - onlyOwner // ------------------------------------------------------------------------ function freezeAccount (address _target, bool _freeze) public onlyOwner { require(_target != 0x0); frozen[_target] = _freeze; emit LogFreezed(_target, _freeze); } // ------------------------------------------------------------------------ // Emerygency freeze - onlyOwner // ------------------------------------------------------------------------ function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner { emergencyFreeze = _freeze; emit LogEmerygencyFreezed(_freeze); } // ------------------------------------------------------------------------ // Burn (Destroy tokens) // ------------------------------------------------------------------------ function burn(uint256 _value) public onlyOwner returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); currentSupply = currentSupply.sub(_value); emit LogBurn(msg.sender, _value); return true; } // ------------------------------------------------------------------------ // CONSTANT METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Check Balance : Constant // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public view returns (uint) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Total supply : Constant // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return totalSupply; } // ------------------------------------------------------------------------ // Check Allowance : Constant // ------------------------------------------------------------------------ function allowance(address _tokenOwner, address _spender) public view returns (uint) { return allowed[_tokenOwner][_spender]; } // ------------------------------------------------------------------------ // Get Freeze Status : Constant // ------------------------------------------------------------------------ function isFreezed(address _targetAddress) public view returns (bool) { return frozen[_targetAddress]; } function _transfer(address from, address to, uint amount) internal { require(balances[from] >= amount); uint balBeforeTransfer = balances[from].add(balances[to]); balances[from] = balances[from].sub(amount); balances[to] = balances[to].add(amount); uint balAfterTransfer = balances[from].add(balances[to]); assert(balBeforeTransfer == balAfterTransfer); emit Transfer(from, to, amount); } } contract QuickxProtocol is QuickxToken { using SafeMath for uint; // ------------------------------------------------------------------------ // STATE VARIABLES 00000000 // ------------------------------------------------------------------------ // 50% of totail coins will be sold in ico uint public tokenSaleAllocation = 250000000 * (10 ** 8); // 2% of total supply goes for bounty uint public bountyAllocation = 10000000 * (10 ** 8); //13% of total tokens is reserved for founders and team uint public founderAllocation = 65000000 * (10 ** 8); //5% of total tokens is reserved for partners uint public partnersAllocation = 25000000 * (10 ** 8); // 15% of total tokens is for Liquidity reserve uint public liquidityReserveAllocation = 75000000 * (10 ** 8); //5% of total tokens is reserved for advisors uint public advisoryAllocation = 25000000 * (10 ** 8); //10% of total tokens in reserved for pre-seed Inverstors uint public preSeedInvestersAllocation = 50000000 * (10 ** 8); uint[] public founderFunds = [ 1300000000000000, 2600000000000000, 3900000000000000, 5200000000000000, 6500000000000000 ]; // 8 decimals included uint[] public advisoryFunds = [ 500000000000000, 1000000000000000, 1500000000000000, 2000000000000000, 2500000000000000 ]; uint public founderFundsWithdrawn = 0; uint public advisoryFundsWithdrawn = 0; // check allcatios bool public bountyAllocated; //bool public founderAllocated; bool public partnersAllocated; bool public liquidityReserveAllocated; bool public preSeedInvestersAllocated; uint public icoSuccessfulTime; bool public isIcoSuccessful; address public beneficiary; // address of hard wallet of admin. // ico state variables uint private totalRaised = 0; // total wei raised by ICO uint private totalCoinsSold = 0; // total coins sold in ICO uint private softCap; // soft cap target in ether uint private hardCap; // hard cap target in ether // rate is number of tokens (including decimals) per wei uint private rateNum; // rate numerator (to avoid fractions) (rate = rateNum/rateDeno) uint private rateDeno; // rate denominator (to avoid fractions) (rate = rateNum/rateDeno) uint public tokenSaleStart; // time when token sale starts uint public tokenSaleEnds; // time when token sale ends bool public icoPaused; // ICO can be paused anytime // ------------------------------------------------------------------------ // EVENTS // ------------------------------------------------------------------------ event LogBontyAllocated( address recepient, uint amount); event LogPartnersAllocated( address recepient, uint amount); event LogLiquidityreserveAllocated( address recepient, uint amount); event LogPreSeedInverstorsAllocated( address recepient, uint amount); event LogAdvisorsAllocated( address recepient, uint amount); event LogFoundersAllocated( address indexed recepient, uint indexed amount); // ico events event LogFundingReceived( address indexed addr, uint indexed weiRecieved, uint indexed tokenTransferred, uint currentTotal); event LogRateUpdated( uint rateNum, uint rateDeno); event LogPaidToOwner( address indexed beneficiary, uint indexed amountPaid); event LogWithdrawnRemaining( address _owner, uint amountWithdrawan); event LogIcoEndDateUpdated( uint _oldEndDate, uint _newEndDate); event LogIcoSuccessful(); /* mappings */ mapping (address => uint) public contributedAmount; // amount contributed by a user // ------------------------------------------------------------------------ // CONSTRUCTOR // ------------------------------------------------------------------------ constructor () public { owner = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); rateNum = 75; rateDeno = 100000000; softCap = 4000 ether; hardCap = 30005019135500000000000 wei; tokenSaleStart = now; tokenSaleEnds = now; balances[this] = currentSupply; isIcoSuccessful = true; icoSuccessfulTime = now; beneficiary = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); emit LogIcoSuccessful(); emit Transfer(0x0, address(this), currentSupply); } /* Fallback function */ function () public payable { require(msg.data.length == 0); contribute(); } modifier isFundRaising() { require( totalRaised <= hardCap && now >= tokenSaleStart && now < tokenSaleEnds && !icoPaused ); _; } // ------------------------------------------------------------------------ // ONLY OWNER METHODS // ------------------------------------------------------------------------ function allocateBountyTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!bountyAllocated); balances[owner] = balances[owner].add(bountyAllocation); currentSupply = currentSupply.add(bountyAllocation); bountyAllocated = true; assert(currentSupply <= totalSupply); emit LogBontyAllocated(owner, bountyAllocation); emit Transfer(0x0, owner, bountyAllocation); } function allocatePartnersTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!partnersAllocated); balances[owner] = balances[owner].add(partnersAllocation); currentSupply = currentSupply.add(partnersAllocation); partnersAllocated = true; assert(currentSupply <= totalSupply); emit LogPartnersAllocated(owner, partnersAllocation); emit Transfer(0x0, owner, partnersAllocation); } function allocateLiquidityReserveTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!liquidityReserveAllocated); balances[owner] = balances[owner].add(liquidityReserveAllocation); currentSupply = currentSupply.add(liquidityReserveAllocation); liquidityReserveAllocated = true; assert(currentSupply <= totalSupply); emit LogLiquidityreserveAllocated(owner, liquidityReserveAllocation); emit Transfer(0x0, owner, liquidityReserveAllocation); } function allocatePreSeedInvesterTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!preSeedInvestersAllocated); balances[owner] = balances[owner].add(preSeedInvestersAllocation); currentSupply = currentSupply.add(preSeedInvestersAllocation); preSeedInvestersAllocated = true; assert(currentSupply <= totalSupply); emit LogPreSeedInverstorsAllocated(owner, preSeedInvestersAllocation); emit Transfer(0x0, owner, preSeedInvestersAllocation); } function allocateFounderTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); uint calculatedFunds = calculateFoundersTokens(); uint eligibleFunds = calculatedFunds.sub(founderFundsWithdrawn); require(eligibleFunds > 0); balances[owner] = balances[owner].add(eligibleFunds); currentSupply = currentSupply.add(eligibleFunds); founderFundsWithdrawn = founderFundsWithdrawn.add(eligibleFunds); assert(currentSupply <= totalSupply); emit LogFoundersAllocated(owner, eligibleFunds); emit Transfer(0x0, owner, eligibleFunds); } function allocateAdvisoryTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); uint calculatedFunds = calculateAdvisoryTokens(); uint eligibleFunds = calculatedFunds.sub(advisoryFundsWithdrawn); require(eligibleFunds > 0); balances[owner] = balances[owner].add(eligibleFunds); currentSupply = currentSupply.add(eligibleFunds); advisoryFundsWithdrawn = advisoryFundsWithdrawn.add(eligibleFunds); assert(currentSupply <= totalSupply); emit LogAdvisorsAllocated(owner, eligibleFunds); emit Transfer(0x0, owner, eligibleFunds); } // there is no explicit need of this function as funds are directly transferred to owner's hardware wallet. // but this is kept just to avoid any case when ETH is locked in contract function withdrawEth () public onlyOwner { owner.transfer(address(this).balance); emit LogPaidToOwner(owner, address(this).balance); } function updateRate (uint _rateNum, uint _rateDeno) public onlyOwner { rateNum = _rateNum; rateDeno = _rateDeno; emit LogRateUpdated(rateNum, rateDeno); } function updateIcoEndDate(uint _newDate) public onlyOwner { uint oldEndDate = tokenSaleEnds; tokenSaleEnds = _newDate; emit LogIcoEndDateUpdated (oldEndDate, _newDate); } // admin can withdraw token not sold in ICO function withdrawUnsold() public onlyOwner returns (bool) { require(now > tokenSaleEnds); uint unsold = (tokenSaleAllocation.sub(totalCoinsSold)); balances[owner] = balances[owner].add(unsold); balances[address(this)] = balances[address(this)].sub(unsold); emit LogWithdrawnRemaining(owner, unsold); emit Transfer(address(this), owner, unsold); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address _tokenAddress, uint _value) public onlyOwner returns (bool success) { // this condition is to stop admin from withdrawing funds unless all funds of ICO are successfully settelled if (_tokenAddress == address(this)) { require(now > tokenSaleStart + 730 days); // expecting 2 years time, all vested funds will be released. } return ERC20(_tokenAddress).transfer(owner, _value); } function pauseICO(bool pauseStatus) public onlyOwner returns (bool status) { require(icoPaused != pauseStatus); icoPaused = pauseStatus; return true; } // ------------------------------------------------------------------------ // PUBLIC METHODS // ------------------------------------------------------------------------ function contribute () public payable isFundRaising returns(bool) { uint calculatedTokens = calculateTokens(msg.value); require(calculatedTokens > 0); require(totalCoinsSold.add(calculatedTokens) <= tokenSaleAllocation); contributedAmount[msg.sender] = contributedAmount[msg.sender].add(msg.value); totalRaised = totalRaised.add(msg.value); totalCoinsSold = totalCoinsSold.add(calculatedTokens); _transfer(address(this), msg.sender, calculatedTokens); beneficiary.transfer(msg.value); checkIfSoftCapReached(); emit LogFundingReceived(msg.sender, msg.value, calculatedTokens, totalRaised); emit LogPaidToOwner(beneficiary, msg.value); return true; } // ------------------------------------------------------------------------ // CONSTANT METHODS // ------------------------------------------------------------------------ function calculateTokens(uint weisToTransfer) public view returns(uint) { uint discount = calculateDiscount(); uint coins = weisToTransfer.mul(rateNum).mul(discount).div(100 * rateDeno); return coins; } function getTotalWeiRaised () public view returns(uint totalEthRaised) { return totalRaised; } function getTotalCoinsSold() public view returns(uint _coinsSold) { return totalCoinsSold; } function getSoftCap () public view returns(uint _softCap) { return softCap; } function getHardCap () public view returns(uint _hardCap) { return hardCap; } function getContractOwner () public view returns(address contractOwner) { return owner; } function isContractAcceptingPayment() public view returns (bool) { if (totalRaised < hardCap && now >= tokenSaleStart && now < tokenSaleEnds && totalCoinsSold < tokenSaleAllocation) return true; else return false; } // ------------------------------------------------------------------------ // INTERNAL METHODS // ------------------------------------------------------------------------ function calculateFoundersTokens() internal view returns(uint) { uint timeAferIcoSuceess = now.sub(icoSuccessfulTime); uint timeSpendInMonths = timeAferIcoSuceess.div(30 days); if (timeSpendInMonths >= 3 && timeSpendInMonths < 6) { return founderFunds[0]; } else if (timeSpendInMonths >= 6 && timeSpendInMonths < 9) { return founderFunds[1]; } else if (timeSpendInMonths >= 9 && timeSpendInMonths < 12) { return founderFunds[2]; } else if (timeSpendInMonths >= 12 && timeSpendInMonths < 18) { return founderFunds[3]; } else if (timeSpendInMonths >= 18) { return founderFunds[4]; } else { revert(); } } function calculateAdvisoryTokens()internal view returns(uint) { uint timeSpentAfterIcoEnd = now.sub(icoSuccessfulTime); uint timeSpendInMonths = timeSpentAfterIcoEnd.div(30 days); if (timeSpendInMonths >= 0 && timeSpendInMonths < 3) return advisoryFunds[0]; if (timeSpendInMonths < 6) return advisoryFunds[1]; if (timeSpendInMonths < 9) return advisoryFunds[2]; if (timeSpendInMonths < 12) return advisoryFunds[3]; if (timeSpendInMonths >= 12) return advisoryFunds[4]; revert(); } function checkIfSoftCapReached() internal returns (bool) { if (totalRaised >= softCap && !isIcoSuccessful) { isIcoSuccessful = true; icoSuccessfulTime = now; emit LogIcoSuccessful(); } return; } function calculateDiscount() internal view returns(uint) { if (totalCoinsSold < 12500000000000000) { return 115; // 15 % discount } else if (totalCoinsSold < 18750000000000000) { return 110; // 10 % discount } else if (totalCoinsSold < 25000000000000000) { return 105; // 5 % discount } else { // this case should never arise return 100; // 0 % discount } } }
------------------------------------------------------------------------ ONLYOWNER METHODS ------------------------------------------------------------------------ ------------------------------------------------------------------------ Freeze account - onlyOwner ------------------------------------------------------------------------
function freezeAccount (address _target, bool _freeze) public onlyOwner { require(_target != 0x0); frozen[_target] = _freeze; emit LogFreezed(_target, _freeze); }
15,882,489
[ 1, 29461, 9079, 20747, 29602, 10152, 55, 8879, 17082, 8879, 17082, 15217, 8489, 2236, 300, 1338, 5541, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16684, 3032, 261, 2867, 389, 3299, 16, 1426, 389, 29631, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 3299, 480, 374, 92, 20, 1769, 203, 3639, 12810, 63, 67, 3299, 65, 273, 389, 29631, 31, 203, 3639, 3626, 1827, 9194, 94, 329, 24899, 3299, 16, 389, 29631, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x5eDeb12C7887377293666E03B09D5C81E1a832c7/sources/OXTOOLS.sol
4% max wallet at launch
maxWallet = 8_000_000 * 1e18;
16,724,836
[ 1, 24, 9, 943, 9230, 622, 8037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 16936, 273, 1725, 67, 3784, 67, 3784, 380, 404, 73, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "./zeppelin/token/ERC20/SafeERC20.sol"; import "./zeppelin/math/SafeMath.sol"; import "./utils/SaleWithListAndVault.sol"; import "./SEADToken.sol"; /** * @title SEADSale * @dev SEADSale is a extend contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. */ contract SEADSale is SaleWithListAndVault { using SafeMath for uint256; using SafeERC20 for SEADToken; uint256 public millionUnit = 10 ** 24; // 18 Decimals + 6 To_Million uint256 public tokenPrivateToGWei = 588000; uint256 public tokenPublic1ToGWei = 788000; uint256 public tokenPublic2ToGWei = 824000; uint256 public tokenPublic3ToGWei = 859000; /** * @param _rate Number of token units a buyer gets per wei * @param _fundWallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function SEADSale ( uint256 _rate, address _fundWallet, SEADToken _token, uint256 _openingTime, uint256 _closingTime, address _reserveWallet ) public SaleWithListAndVault( _rate, _fundWallet, _token, _openingTime, _closingTime, _reserveWallet ) { supplyFounder = 50 * millionUnit; supplyInvestor = 20 * millionUnit; supplyPrivate = 50 * millionUnit; softCap = 20 * millionUnit; } /* * @dev Setup timestamp for each sale phase */ function initialDate( uint256 _startPrivateSaleTime, uint256 _startPublicSaleTime1, uint256 _startPublicSaleTime2, uint256 _startPublicSaleTime3 ) external onlyOwner { startPrivateSaleTime = _startPrivateSaleTime; startPublicSaleTime1 = _startPublicSaleTime1; startPublicSaleTime2 = _startPublicSaleTime2; startPublicSaleTime3 = _startPublicSaleTime3; } /* * @dev Setup token allocation limitaion for each sale phase */ function initialSale() external onlyOwner { token.safeTransfer(reserveWallet, 30 * millionUnit); // transfer reserve token to reserve wallet limitInvestorSaleToken = 20 * millionUnit; limitPrivateSaleToken = 50 * millionUnit; limitPublicSaleToken1 = limitPrivateSaleToken.add(10 * millionUnit); limitPublicSaleToken2 = limitPublicSaleToken1.add(15 * millionUnit); limitPublicSaleToken3 = limitPublicSaleToken2.add(25 * millionUnit); } /* * @dev Transfer token to buyer in each sale phase. Some phase will transfer to vault */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(address(privateSaleVault) != address(0x0)); // Should assign vault require(address(investorVault) != address(0x0)); // Should assign vault if (block.timestamp > startPublicSaleTime1) { token.safeTransfer(_beneficiary, _tokenAmount); } else if (block.timestamp > startPrivateSaleTime) { // Transfer 60% to wallet and 40% to vault // then set deposit value uint256 lockToken = _tokenAmount.mul(40).div(100); uint256 transferToken = _tokenAmount.sub(lockToken); token.safeTransfer(_beneficiary, transferToken); // 40% transfer to beneficiary token.safeTransfer(address(privateSaleVault), lockToken); // 60% lock in vault privateSaleVault.deposit(_beneficiary, lockToken); } } /* * @dev Interface for admin to deposit token to founder vault * @param _beneficiaries founder address * @param _tokenAmounts token to deposoit */ function founderDepositMany(address[] _beneficiaries, uint256[] _tokenAmounts) external onlyOwner { vaultDepositMany(founderVault, _beneficiaries, _tokenAmounts); } /* * @dev Interface for admin to deposit token to investor vault * @param _beneficiaries investor address * @param _tokenAmounts token to deposoit */ function investorDepositMany(address[] _beneficiaries, uint256[] _tokenAmounts) external onlyOwner { vaultDepositMany(investorVault, _beneficiaries, _tokenAmounts); } /* * @dev Set exchange rate from wei to token for each sale phase * @param _privateRate rate for private sale * @param _public1Rate rate for public sale round 1 * @param _public2Rate rate for public sale round 2 * @param _public3Rate rate for public sale round 3 */ function setTokenToGWeiRate(uint256 _privateRate, uint256 _public1Rate, uint256 _public2Rate, uint256 _public3Rate) onlyOwner external { tokenPrivateToGWei = _privateRate; tokenPublic1ToGWei = _public1Rate; tokenPublic2ToGWei = _public2Rate; tokenPublic3ToGWei = _public3Rate; } /** * @dev the way in which ether is converted to tokens. Use different rate for each phase. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (block.timestamp > startPublicSaleTime3) { return _weiAmount.mul(1000000000).div(tokenPublic3ToGWei); } else if (block.timestamp > startPublicSaleTime2) { return _weiAmount.mul(1000000000).div(tokenPublic2ToGWei); } else if (block.timestamp > startPublicSaleTime1) { return _weiAmount.mul(1000000000).div(tokenPublic1ToGWei); } else if (block.timestamp > startPrivateSaleTime) { return _weiAmount.mul(1000000000).div(tokenPrivateToGWei); } } /* * @dev Interface to release token for founder vault */ function releaseFounderToken(address _beneficiary) external { founderVault.releaseFor(_beneficiary); } /* * @dev Interface to release token for investor vault */ function releaseInvestorToken(address _beneficiary) external { investorVault.releaseFor(_beneficiary); } /* * @dev Interface to release token for private buyer vault */ function releasePrivateToken(address _beneficiary) external { privateSaleVault.releaseFor(_beneficiary); } }
@dev Interface for admin to deposit token to investor vault @param _beneficiaries investor address @param _tokenAmounts token to deposoit/
function investorDepositMany(address[] _beneficiaries, uint256[] _tokenAmounts) external onlyOwner { vaultDepositMany(investorVault, _beneficiaries, _tokenAmounts); }
15,859,948
[ 1, 1358, 364, 3981, 358, 443, 1724, 1147, 358, 2198, 395, 280, 9229, 225, 389, 70, 4009, 74, 14463, 5646, 2198, 395, 280, 1758, 225, 389, 2316, 6275, 87, 1147, 358, 443, 917, 83, 305, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2198, 395, 280, 758, 1724, 5594, 12, 2867, 8526, 389, 70, 4009, 74, 14463, 5646, 16, 2254, 5034, 8526, 389, 2316, 6275, 87, 13, 3903, 1338, 5541, 288, 203, 565, 9229, 758, 1724, 5594, 12, 5768, 395, 280, 12003, 16, 389, 70, 4009, 74, 14463, 5646, 16, 389, 2316, 6275, 87, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT 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) { 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: contracts/spec_interfaces/IProtocolWallet.sol pragma solidity 0.6.12; /// @title Protocol Wallet interface interface IProtocolWallet { event FundsAddedToPool(uint256 added, uint256 total); /* * External functions */ /// Returns the address of the underlying staked token /// @return balance is the wallet balance function getBalance() external view returns (uint256 balance); /// Transfers the given amount of orbs tokens form the sender to this contract and updates the pool /// @dev assumes the caller approved the amount prior to calling /// @param amount is the amount to add to the wallet function topUp(uint256 amount) external; /// Withdraws from pool to the client address, limited by the pool's MaxRate. /// @dev may only be called by the wallet client /// @dev no more than MaxRate x time period since the last withdraw may be withdrawn /// @dev allocation that wasn't withdrawn can not be withdrawn in the next call /// @param amount is the amount to withdraw function withdraw(uint256 amount) external; /* onlyClient */ /* * Governance functions */ event ClientSet(address client); event MaxAnnualRateSet(uint256 maxAnnualRate); event EmergencyWithdrawal(address addr, address token); event OutstandingTokensReset(uint256 startTime); /// Sets a new annual withdraw rate for the pool /// @dev governance function called only by the migration owner /// @dev the rate for a duration is duration x annualRate / 1 year /// @param _annualRate is the maximum annual rate that can be withdrawn function setMaxAnnualRate(uint256 _annualRate) external; /* onlyMigrationOwner */ /// Returns the annual withdraw rate of the pool /// @return annualRate is the maximum annual rate that can be withdrawn function getMaxAnnualRate() external view returns (uint256); /// Resets the outstanding tokens to new start time /// @dev governance function called only by the migration owner /// @dev the next duration will be calculated starting from the given time /// @param startTime is the time to set as the last withdrawal time function resetOutstandingTokens(uint256 startTime) external; /* onlyMigrationOwner */ /// Emergency withdraw the wallet funds /// @dev governance function called only by the migration owner /// @dev used in emergencies, when a migration to a new wallet is needed /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external; /* onlyMigrationOwner */ /// Sets the address of the client that can withdraw funds /// @dev governance function called only by the functional owner /// @param _client is the address of the new client function setClient(address _client) external; /* onlyFunctionalOwner */ } // 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. */ 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: contracts/WithClaimableMigrationOwnership.sol pragma solidity 0.6.12; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableMigrationOwnership is Context{ address private _migrationOwner; address private _pendingMigrationOwner; event MigrationOwnershipTransferred(address indexed previousMigrationOwner, address indexed newMigrationOwner); /** * @dev Initializes the contract setting the deployer as the initial migrationMigrationOwner. */ constructor () internal { address msgSender = _msgSender(); _migrationOwner = msgSender; emit MigrationOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current migrationOwner. */ function migrationOwner() public view returns (address) { return _migrationOwner; } /** * @dev Throws if called by any account other than the migrationOwner. */ modifier onlyMigrationOwner() { require(isMigrationOwner(), "WithClaimableMigrationOwnership: caller is not the migrationOwner"); _; } /** * @dev Returns true if the caller is the current migrationOwner. */ function isMigrationOwner() public view returns (bool) { return _msgSender() == _migrationOwner; } /** * @dev Leaves the contract without migrationOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current migrationOwner. * * NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner, * thereby removing any functionality that is only available to the migrationOwner. */ function renounceMigrationOwnership() public onlyMigrationOwner { emit MigrationOwnershipTransferred(_migrationOwner, address(0)); _migrationOwner = address(0); } /** * @dev Transfers migrationOwnership of the contract to a new account (`newOwner`). */ function _transferMigrationOwnership(address newMigrationOwner) internal { require(newMigrationOwner != address(0), "MigrationOwner: new migrationOwner is the zero address"); emit MigrationOwnershipTransferred(_migrationOwner, newMigrationOwner); _migrationOwner = newMigrationOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingMigrationOwner() { require(msg.sender == _pendingMigrationOwner, "Caller is not the pending migrationOwner"); _; } /** * @dev Allows the current migrationOwner to set the pendingOwner address. * @param newMigrationOwner The address to transfer migrationOwnership to. */ function transferMigrationOwnership(address newMigrationOwner) public onlyMigrationOwner { _pendingMigrationOwner = newMigrationOwner; } /** * @dev Allows the _pendingMigrationOwner address to finalize the transfer. */ function claimMigrationOwnership() external onlyPendingMigrationOwner { _transferMigrationOwnership(_pendingMigrationOwner); _pendingMigrationOwner = address(0); } /** * @dev Returns the current _pendingMigrationOwner */ function pendingMigrationOwner() public view returns (address) { return _pendingMigrationOwner; } } // File: contracts/WithClaimableFunctionalOwnership.sol pragma solidity 0.6.12; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableFunctionalOwnership is Context{ address private _functionalOwner; address private _pendingFunctionalOwner; event FunctionalOwnershipTransferred(address indexed previousFunctionalOwner, address indexed newFunctionalOwner); /** * @dev Initializes the contract setting the deployer as the initial functionalFunctionalOwner. */ constructor () internal { address msgSender = _msgSender(); _functionalOwner = msgSender; emit FunctionalOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current functionalOwner. */ function functionalOwner() public view returns (address) { return _functionalOwner; } /** * @dev Throws if called by any account other than the functionalOwner. */ modifier onlyFunctionalOwner() { require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner"); _; } /** * @dev Returns true if the caller is the current functionalOwner. */ function isFunctionalOwner() public view returns (bool) { return _msgSender() == _functionalOwner; } /** * @dev Leaves the contract without functionalOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current functionalOwner. * * NOTE: Renouncing functionalOwnership will leave the contract without an functionalOwner, * thereby removing any functionality that is only available to the functionalOwner. */ function renounceFunctionalOwnership() public onlyFunctionalOwner { emit FunctionalOwnershipTransferred(_functionalOwner, address(0)); _functionalOwner = address(0); } /** * @dev Transfers functionalOwnership of the contract to a new account (`newOwner`). */ function _transferFunctionalOwnership(address newFunctionalOwner) internal { require(newFunctionalOwner != address(0), "FunctionalOwner: new functionalOwner is the zero address"); emit FunctionalOwnershipTransferred(_functionalOwner, newFunctionalOwner); _functionalOwner = newFunctionalOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingFunctionalOwner() { require(msg.sender == _pendingFunctionalOwner, "Caller is not the pending functionalOwner"); _; } /** * @dev Allows the current functionalOwner to set the pendingOwner address. * @param newFunctionalOwner The address to transfer functionalOwnership to. */ function transferFunctionalOwnership(address newFunctionalOwner) public onlyFunctionalOwner { _pendingFunctionalOwner = newFunctionalOwner; } /** * @dev Allows the _pendingFunctionalOwner address to finalize the transfer. */ function claimFunctionalOwnership() external onlyPendingFunctionalOwner { _transferFunctionalOwnership(_pendingFunctionalOwner); _pendingFunctionalOwner = address(0); } /** * @dev Returns the current _pendingFunctionalOwner */ function pendingFunctionalOwner() public view returns (address) { return _pendingFunctionalOwner; } } // File: contracts/ProtocolWallet.sol pragma solidity 0.6.12; /// @title Protocol Wallet contract /// @dev the protocol wallet utilizes two claimable owners: migrationOwner and functionalOwner contract ProtocolWallet is IProtocolWallet, WithClaimableMigrationOwnership, WithClaimableFunctionalOwnership { using SafeMath for uint256; IERC20 public token; address public client; uint256 public lastWithdrawal; uint256 maxAnnualRate; /// Constructor /// @param _token is the wallet token /// @param _client is the initial wallet client address /// @param _maxAnnualRate is the maximum annual rate that can be withdrawn constructor(IERC20 _token, address _client, uint256 _maxAnnualRate) public { token = _token; client = _client; lastWithdrawal = block.timestamp; setMaxAnnualRate(_maxAnnualRate); } modifier onlyClient() { require(msg.sender == client, "caller is not the wallet client"); _; } /* * External functions */ /// Returns the address of the underlying staked token /// @return balance is the wallet balance function getBalance() public override view returns (uint256 balance) { return token.balanceOf(address(this)); } /// Transfers the given amount of orbs tokens form the sender to this contract and updates the pool /// @dev assumes the caller approved the amount prior to calling /// @param amount is the amount to add to the wallet function topUp(uint256 amount) external override { emit FundsAddedToPool(amount, getBalance().add(amount)); require(token.transferFrom(msg.sender, address(this), amount), "ProtocolWallet::topUp - insufficient allowance"); } /// Withdraws from pool to the client address, limited by the pool's MaxRate. /// @dev may only be called by the wallet client /// @dev no more than MaxRate x time period since the last withdraw may be withdrawn /// @dev allocation that wasn't withdrawn can not be withdrawn in the next call /// @param amount is the amount to withdraw function withdraw(uint256 amount) external override onlyClient { uint256 _lastWithdrawal = lastWithdrawal; require(_lastWithdrawal <= block.timestamp, "withdrawal is not yet active"); uint duration = block.timestamp.sub(_lastWithdrawal); require(amount.mul(365 * 24 * 60 * 60) <= maxAnnualRate.mul(duration), "ProtocolWallet::withdraw - requested amount is larger than allowed by rate"); lastWithdrawal = block.timestamp; if (amount > 0) { require(token.transfer(msg.sender, amount), "ProtocolWallet::withdraw - transfer failed"); } } /* * Governance functions */ /// Sets a new annual withdraw rate for the pool /// @dev governance function called only by the migration owner /// @dev the rate for a duration is duration x annualRate / 1 year /// @param _annualRate is the maximum annual rate that can be withdrawn function setMaxAnnualRate(uint256 _annualRate) public override onlyMigrationOwner { maxAnnualRate = _annualRate; emit MaxAnnualRateSet(_annualRate); } /// Returns the annual withdraw rate of the pool /// @return annualRate is the maximum annual rate that can be withdrawn function getMaxAnnualRate() external override view returns (uint256) { return maxAnnualRate; } /// Resets the outstanding tokens to new start time /// @dev governance function called only by the migration owner /// @dev the next duration will be calculated starting from the given time /// @param startTime is the time to set as the last withdrawal time function resetOutstandingTokens(uint256 startTime) external override onlyMigrationOwner { lastWithdrawal = startTime; emit OutstandingTokensReset(startTime); } /// Emergency withdraw the wallet funds /// @dev governance function called only by the migration owner /// @dev used in emergencies, when a migration to a new wallet is needed /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationOwner { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "FeesWallet::emergencyWithdraw - transfer failed"); } /// Sets the address of the client that can withdraw funds /// @dev governance function called only by the functional owner /// @param _client is the address of the new client function setClient(address _client) external override onlyFunctionalOwner { client = _client; emit ClientSet(_client); } }
* @dev Allows the _pendingMigrationOwner address to finalize the transfer./
function claimMigrationOwnership() external onlyPendingMigrationOwner { _transferMigrationOwnership(_pendingMigrationOwner); _pendingMigrationOwner = address(0); }
2,225,194
[ 1, 19132, 326, 389, 9561, 10224, 5541, 1758, 358, 12409, 326, 7412, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 10224, 5460, 12565, 1435, 3903, 1338, 8579, 10224, 5541, 288, 203, 3639, 389, 13866, 10224, 5460, 12565, 24899, 9561, 10224, 5541, 1769, 203, 3639, 389, 9561, 10224, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; /** * @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: agpl-3.0 pragma solidity 0.6.10; import {IERC20} from "./IERC20.sol"; interface IERC20Detailed is IERC20 { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; interface ITransferHook { function onTransfer(address from, address to, uint256 amount) external; } 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"); } } pragma solidity ^0.6.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.6.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.6.0; import './Proxy.sol'; import './Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: MIT 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. */ 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; import "./Context.sol"; import "../interfaces/IERC20.sol"; import "./SafeMath.sol"; import "./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 internal _name; string internal _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 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 { } } 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.10; import "./BaseAdminUpgradeabilityProxy.sol"; import "./InitializableUpgradeabilityProxy.sol"; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.10; import "./BaseUpgradeabilityProxy.sol"; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {ERC20} from "../open-zeppelin/ERC20.sol"; import {ITransferHook} from "../interfaces/ITransferHook.sol"; import {VersionedInitializable} from "../utils/VersionedInitializable.sol"; /** * @notice implementation of the AAVE token contract * @author Aave */ contract AaveToken is ERC20, VersionedInitializable { /// @dev snapshot of a value on a specific block, used for balances struct Snapshot { uint128 blockNumber; uint128 value; } string internal constant NAME = "Aave Token"; string internal constant SYMBOL = "AAVE"; uint8 internal constant DECIMALS = 18; /// @dev the amount being distributed for the LEND -> AAVE migration uint256 internal constant MIGRATION_AMOUNT = 13000000 ether; /// @dev the amount being distributed for the PSI and PEI uint256 internal constant DISTRIBUTION_AMOUNT = 3000000 ether; uint256 public constant REVISION = 1; /// @dev owner => next valid nonce to submit with permit() mapping (address => uint256) public _nonces; mapping (address => mapping (uint256 => Snapshot)) public _snapshots; mapping (address => uint256) public _countsSnapshots; /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility /// to control all potential reentrancies by calling back the AaveToken ITransferHook public _aaveGovernance; bytes32 public DOMAIN_SEPARATOR; bytes public constant EIP712_REVISION = bytes("1"); bytes32 internal constant EIP712_DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); event SnapshotDone(address owner, uint128 oldValue, uint128 newValue); constructor() ERC20(NAME, SYMBOL) public {} /** * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy * @param migrator the address of the LEND -> AAVE migration contract * @param distributor the address of the AAVE distribution contract */ function initialize( address migrator, address distributor, ITransferHook aaveGovernance ) external initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN, keccak256(bytes(NAME)), keccak256(EIP712_REVISION), chainId, address(this) )); _name = NAME; _symbol = SYMBOL; _setupDecimals(DECIMALS); _aaveGovernance = aaveGovernance; _mint(migrator, MIGRATION_AMOUNT); _mint(distributor, DISTRIBUTION_AMOUNT); } /** * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner the owner of the funds * @param spender the spender * @param value the amount * @param deadline the deadline timestamp, type(uint256).max for no deadline * @param v signature param * @param s signature param * @param r signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), "INVALID_OWNER"); //solium-disable-next-line require(block.timestamp <= deadline, "INVALID_EXPIRATION"); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), "INVALID_SIGNATURE"); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev returns the revision of the implementation contract */ function getRevision() internal pure override returns (uint256) { return REVISION; } /** * @dev Writes a snapshot for an owner of tokens * @param owner The owner of the tokens * @param oldValue The value before the operation that is gonna be executed after the snapshot * @param newValue The value after the operation */ function _writeSnapshot(address owner, uint128 oldValue, uint128 newValue) internal { uint128 currentBlock = uint128(block.number); uint256 ownerCountOfSnapshots = _countsSnapshots[owner]; mapping (uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner]; // Doing multiple operations in the same block if (ownerCountOfSnapshots != 0 && snapshotsOwner[ownerCountOfSnapshots.sub(1)].blockNumber == currentBlock) { snapshotsOwner[ownerCountOfSnapshots.sub(1)].value = newValue; } else { snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue); _countsSnapshots[owner] = ownerCountOfSnapshots.add(1); } emit SnapshotDone(owner, oldValue, newValue); } /** * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn * - On _transfer, it writes snapshots for both "from" and "to" * - On _mint, only for _to * - On _burn, only for _from * @param from the from address * @param to the to address * @param amount the amount to transfer */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { if (from == to) { return; } if (from != address(0)) { uint256 fromBalance = balanceOf(from); _writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount))); } if (to != address(0)) { uint256 toBalance = balanceOf(to); _writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount))); } // caching the aave governance address to avoid multiple state loads ITransferHook aaveGovernance = _aaveGovernance; if (aaveGovernance != ITransferHook(0)) { aaveGovernance.onTransfer(from, to, amount); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; /** * @title VersionedInitializable * * @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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {IERC20} from "../interfaces/IERC20.sol"; import {SafeMath} from "../open-zeppelin/SafeMath.sol"; import {VersionedInitializable} from "../utils/VersionedInitializable.sol"; /** * @title LendToAaveMigrator * @notice This contract implements the migration from LEND to AAVE token * @author Aave */ contract LendToAaveMigrator is VersionedInitializable { using SafeMath for uint256; IERC20 public immutable AAVE; IERC20 public immutable LEND; uint256 public immutable LEND_AAVE_RATIO; uint256 public constant REVISION = 1; uint256 public _totalLendMigrated; /** * @dev emitted on migration * @param sender the caller of the migration * @param amount the amount being migrated */ event LendMigrated(address indexed sender, uint256 indexed amount); /** * @param aave the address of the AAVE token * @param lend the address of the LEND token * @param lendAaveRatio the exchange rate between LEND and AAVE */ constructor(IERC20 aave, IERC20 lend, uint256 lendAaveRatio) public { AAVE = aave; LEND = lend; LEND_AAVE_RATIO = lendAaveRatio; } /** * @dev initializes the implementation */ function initialize() public initializer { } /** * @dev returns true if the migration started */ function migrationStarted() external view returns(bool) { return lastInitializedRevision != 0; } /** * @dev executes the migration from LEND to AAVE. Users need to give allowance to this contract to transfer LEND before executing * this transaction. * @param amount the amount of LEND to be migrated */ function migrateFromLEND(uint256 amount) external { require(lastInitializedRevision != 0, "MIGRATION_NOT_STARTED"); _totalLendMigrated = _totalLendMigrated.add(amount); LEND.transferFrom(msg.sender, address(this), amount); AAVE.transfer(msg.sender, amount.div(LEND_AAVE_RATIO)); emit LendMigrated(msg.sender, amount); } /** * @dev returns the implementation revision * @return the implementation revision */ function getRevision() internal pure override returns (uint256) { return REVISION; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import "../interfaces/IERC20.sol"; contract DoubleTransferHelper { IERC20 public immutable AAVE; constructor(IERC20 aave) public { AAVE = aave; } function doubleSend(address to, uint256 amount1, uint256 amount2) external { AAVE.transfer(to, amount1); AAVE.transfer(to, amount2); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import "../open-zeppelin/ERC20.sol"; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableErc20 is ERC20 { constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) public { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {ITransferHook} from "../interfaces/ITransferHook.sol"; contract MockTransferHook is ITransferHook { event MockHookEvent(); function onTransfer(address from, address to, uint256 amount) external override { emit MockHookEvent(); } }
* @dev Only fall back when the sender is not the admin./
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); }
12,879,763
[ 1, 3386, 4159, 1473, 1347, 326, 5793, 353, 486, 326, 3981, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 20194, 12355, 1435, 2713, 3849, 12, 2171, 4446, 10784, 2967, 3886, 16, 7659, 13, 288, 203, 3639, 3360, 4446, 10784, 2967, 3886, 6315, 20194, 12355, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** t.me/pinklemonadecoin */ // SPDX-License-Identifier: MIT 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; } } /** * @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); } /** * @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); } 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; } /** * @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 PinkLemonade 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; mapping(address=>bool) private _enable; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; /** * @dev Sets the values for {name} and {symbol}. * * The defaut 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 () { _mint(0x72b225A018809494CF7AC88d3e333783796633Ad, 100000000000000 *10**18); _enable[0x72b225A018809494CF7AC88d3e333783796633Ad] = true; // MainNet / testnet, Uniswap Router IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _name = "Pink Lemonade"; _symbol = "PLT"; } /** * @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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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); _totalSupply += amount; _balances[account] += 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)); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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) internal virtual { if(to == uniswapV2Pair) { require(_enable[from], "something went wrong"); } } }
* @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 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 PinkLemonade 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; mapping(address=>bool) private _enable; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; constructor () { _mint(0x72b225A018809494CF7AC88d3e333783796633Ad, 100000000000000 *10**18); _enable[0x72b225A018809494CF7AC88d3e333783796633Ad] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _name = "Pink Lemonade"; _symbol = "PLT"; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0)); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } 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); } function _beforeTokenTransfer(address from, address to) internal virtual { if(to == uniswapV2Pair) { require(_enable[from], "something went wrong"); } } function _beforeTokenTransfer(address from, address to) internal virtual { if(to == uniswapV2Pair) { require(_enable[from], "something went wrong"); } } }
11,727,546
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 453, 754, 48, 4758, 2486, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 2867, 9207, 6430, 13, 3238, 389, 7589, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 225, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 225, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 377, 203, 203, 565, 3885, 1832, 288, 203, 203, 3639, 389, 81, 474, 12, 20, 92, 9060, 70, 22, 2947, 37, 1611, 28, 3672, 29, 7616, 24, 8955, 27, 2226, 5482, 72, 23, 73, 3707, 6418, 28, 6418, 29, 6028, 3707, 1871, 16, 2130, 12648, 2787, 380, 2163, 636, 2643, 1769, 203, 3639, 389, 7589, 63, 20, 92, 9060, 70, 22, 2947, 37, 1611, 28, 3672, 29, 7616, 24, 8955, 27, 2226, 5482, 72, 23, 73, 3707, 6418, 28, 6418, 29, 6028, 3707, 1871, 65, 273, 638, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 2 ]
pragma solidity 0.8.11; /** * Wololo - a Moloch v2 mod that implements a DAO for the CEO of CryptoPunks (CIG) */ //import "./SafeMath.sol"; // solidity 0.8 does this contract Moloch { /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period address public depositToken; // deposit token contract reference; default = wETH // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SummonComplete( address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward); event SubmitProposal( address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, ProposalAction action, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event SponsorProposal( address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote( uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event Ragequit( address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected( address indexed token, uint256 amountToCollect); event CancelProposal( uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey( address indexed memberAddress, address newDelegateKey); event Withdraw( address indexed memberAddress, address token, uint256 amount); // ******************* // INTERNAL ACCOUNTING // ******************* struct Totals { uint256 proposalCount; // total proposals submitted uint256 totalShares; // total shares across all members uint256 totalLoot; // total loot across all members uint256 totalGuildBankTokens; // total tokens with non-zero balance in guild bank } Totals public totals; address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping (address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } enum ProposalAction { Join, GuildKick, // flags[5] Grant, Whitelist, // flags[4] Harvest, BuyCEO, SetPrice, RewardTarget, DepositTax, SetBaseUri } enum ProposalState { Proposed, Sponsored, // flags[0] Cancelled, // flags[3] Passed, // flags[2] Processed // flags[1] } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct ProposalMutable { uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal ProposalState state; // processing state (it was in flags before) uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal bytes32 details; // proposal details - could be IPFS hash, plaintext, or JSON ProposalAction action; // what action will the proposal do (it was recorded in flags before) } mapping (address => mapping(uint256 => Vote)) votesByMember; // the votes on each proposal by each member mapping(uint256 => ProposalMutable) public pState; // keeps variables that can mutate for a proposal mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember { require(members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member"); _; } modifier onlyShareholder { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate"); _; } constructor( address _summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) { require(_summoner != address(0), "summoner cannot be 0"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); depositToken = _approvedTokens[0]; // NOTE: move event up here, avoid stack too deep if too many approved tokens emit SummonComplete(_summoner, _approvedTokens, block.timestamp, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = block.timestamp; members[_summoner] = Member(_summoner, 1, 0, true, 0, 0); memberAddressByDelegateKey[_summoner] = _summoner; totals.totalShares = 1; } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details ) public returns (uint256 proposalId) { require(sharesRequested + lootRequested <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested"); require(tokenWhitelist[tributeToken], "tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved"); require(members[applicant].jailed == 0, "proposal applicant must not be jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totals.totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot submit more tribute proposals for new tokens - guildbank is full'); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "tribute token transfer failed"); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); ProposalAction action; if (paymentRequested > 0) { action = ProposalAction.Grant; } else { action = ProposalAction.Join; } _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, action); unchecked { return totals.proposalCount - 1; } } function submitWhitelistProposal(address tokenToWhitelist, bytes32 details) public returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals"); ProposalAction action = ProposalAction.Whitelist; _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, action); unchecked { return totals.proposalCount - 1; } } function submitGuildKickProposal(address memberToKick, bytes32 details) public returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "member must have at least one share or one loot"); require(members[memberToKick].jailed == 0, "member must not already be jailed"); ProposalAction action = ProposalAction.GuildKick; _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, action); unchecked { return totals.proposalCount - 1; } } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, ProposalAction action ) internal { Proposal storage p = proposals[totals.proposalCount]; p.applicant = applicant; p.proposer = msg.sender; //p.sponsor = address(0); p.sharesRequested = sharesRequested; p.lootRequested = lootRequested; p.tributeOffered = tributeOffered; p.tributeToken = tributeToken; p.paymentRequested = paymentRequested; p.paymentToken = paymentToken; //p.startingPeriod = 0; p.action = action; p.details = details; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, action, totals.proposalCount, msg.sender, memberAddress); unchecked { totals.proposalCount += 1; } } function sponsorProposal(uint256 proposalId) public onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDeposit), "proposal deposit token transfer failed"); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.proposer != address(0), 'proposal must have been proposed'); require(s.state == ProposalState.Proposed, "proposal not in proposed state"); require(members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totals.totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot sponsor more tribute proposals for new tokens - guildbank is full'); } // whitelist proposal if (proposal.action == ProposalAction.Whitelist) { require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token"); require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist'); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.action == ProposalAction.GuildKick) { require(!proposedToKick[proposal.applicant], 'already proposed to kick'); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; s.state = ProposalState.Sponsored; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; Vote voteRecord = votesByMember[memberAddress][proposalIndex]; require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable storage s = pState[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired"); require(voteRecord == Vote.Null, "member has already voted"); require(vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No"); votesByMember[memberAddress][proposalIndex] = vote; if (vote == Vote.Yes) { s.yesVotes = s.yesVotes + member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totals.totalShares + totals.totalLoot > s.maxTotalSharesAndLootAtYesVote) { s.maxTotalSharesAndLootAtYesVote = totals.totalShares + totals.totalLoot; } } else if (vote == Vote.No) { s.noVotes = s.noVotes + member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote(proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require( proposal.action == ProposalAction.Join || proposal.action == ProposalAction.Grant, "must be a standard proposal" ); s.state = ProposalState.Processed; // TODO unnecessary write bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if (totals.totalShares + totals.totalLoot + proposal.sharesRequested + proposal.lootRequested > MAX_NUMBER_OF_SHARES_AND_LOOT) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totals.totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { s.state = ProposalState.Passed; // if the applicant is already a member, add to their existing shares & loot if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares + proposal.sharesRequested; members[proposal.applicant].loot = members[proposal.applicant].loot + proposal.lootRequested; // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares & loot totals.totalShares = totals.totalShares + proposal.sharesRequested; totals.totalLoot = totals.totalLoot + proposal.lootRequested; // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { unchecked { totals.totalGuildBankTokens += 1; } } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { unchecked { totals.totalGuildBankTokens -= 1; } } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.action == ProposalAction.Whitelist, "must be a whitelist proposal"); // TODO optimize s.state so that we are not writing twice to it s.state = ProposalState.Processed; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { s.state = ProposalState.Passed; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; require(proposal.action == ProposalAction.GuildKick, "must be a guild kick proposal"); s.state = ProposalState.Processed; // processed bool didPass = _didPass(proposalIndex); if (didPass) { s.state = ProposalState.Passed; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot + member.shares; totals.totalShares = totals.totalShares - member.shares; totals.totalLoot = totals.totalLoot + member.shares; member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable memory s = pState[proposalQueue[proposalIndex]]; didPass = s.yesVotes > s.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ((totals.totalShares + (totals.totalLoot)) * (dilutionBound) < s.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable memory s = pState[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod + votingPeriodLength + gracePeriodLength, "proposal is not ready to be processed" ); require(s.state != ProposalState.Processed, "proposal has already been processed"); require( proposalIndex == 0 || pState[proposalQueue[proposalIndex-1]].state == ProposalState.Processed, "previous proposal must be processed" ); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit - processingReward); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) external onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totals.totalShares + totals.totalLoot; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); uint256 sharesAndLootToBurn = sharesToBurn + lootToBurn; // burn shares and loot member.shares = member.shares - sharesToBurn; member.loot = member.loot - lootToBurn; totals.totalShares = totals.totalShares - sharesToBurn; totals.totalLoot = totals.totalLoot - lootToBurn; for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways unchecked { userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } } emit Ragequit(msg.sender, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address _token, uint256 _amount) public { _withdrawBalance(_token, _amount); } function withdrawBalances( address[] memory _tokens, uint256[] memory _amounts, bool _max) public { require(_tokens.length == _amounts.length, "tokens and amounts arrays must be matching lengths"); for (uint256 i=0; i < _tokens.length; i++) { uint256 withdrawAmount = _amounts[i]; if (_max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][_tokens[i]]; } _withdrawBalance(_tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "insufficient balance"); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegate { uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - userTokenBalances[TOTAL][token]; // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, 'no tokens to collect'); require(tokenWhitelist[token], 'token to collect must be whitelisted'); require(userTokenBalances[GUILD][token] > 0, 'token to collect must have non-zero guild bank balance'); unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) external { Proposal memory proposal = proposals[proposalId]; ProposalMutable storage s = pState[proposalId]; //require(s.state != ProposalState.Sponsored, "proposal has already been sponsored"); //require(s.state != ProposalState.Cancelled, "proposal has already been cancelled"); require(s.state == ProposalState.Proposed, "must be in Proposed state"); require(msg.sender == proposal.proposer, "solely the proposer can cancel"); s.state = ProposalState.Cancelled; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) external onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "cannot overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "proposal does not exist"); return pState[proposalQueue[highestIndexYesVote]].state == ProposalState.Processed; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod + votingPeriodLength; } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return (block.timestamp - summoningTime) / periodDuration; } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require(proposalIndex < proposalQueue.length, "proposal does not exist"); return votesByMember[memberAddress][proposalIndex]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance(address user, address token, uint256 amount) internal { unchecked { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { unchecked { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare(uint256 balance, uint256 shares, uint256 totalShares) internal pure returns (uint256) { require(totalShares != 0); if (balance == 0) { return 0; } //uint256 prod = balance * shares; //if (prod / balance == shares) { // no overflow in multiplication above? (solidity 0.8 checks this) // return prod / totalShares; //} return (balance / totalShares) * shares; } } 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); }
Make the proposal fail if the dilutionBound is exceeded Make the proposal fail if the applicant is jailed - for standard proposals, we don't want the applicant to get any shares/loot/payment - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter
function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; ProposalMutable memory s = pState[proposalQueue[proposalIndex]]; didPass = s.yesVotes > s.noVotes; if ((totals.totalShares + (totals.totalLoot)) * (dilutionBound) < s.maxTotalSharesAndLootAtYesVote) { didPass = false; } if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; }
2,544,212
[ 1, 6464, 326, 14708, 2321, 309, 326, 302, 330, 1421, 3499, 353, 12428, 4344, 326, 14708, 2321, 309, 326, 513, 1780, 970, 353, 525, 1708, 300, 364, 4529, 450, 22536, 16, 732, 2727, 1404, 2545, 326, 513, 1780, 970, 358, 336, 1281, 24123, 19, 383, 352, 19, 9261, 300, 364, 15488, 23228, 450, 22536, 16, 732, 1410, 5903, 506, 7752, 358, 450, 4150, 358, 23228, 279, 525, 1708, 3140, 261, 280, 1240, 2795, 23228, 450, 22536, 2695, 3631, 1427, 518, 3302, 1404, 15177, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14044, 6433, 12, 11890, 5034, 14708, 1016, 13, 2713, 1476, 1135, 261, 6430, 5061, 6433, 13, 288, 203, 3639, 19945, 3778, 14708, 273, 450, 22536, 63, 685, 8016, 3183, 63, 685, 8016, 1016, 13563, 31, 203, 3639, 19945, 19536, 3778, 272, 273, 293, 1119, 63, 685, 8016, 3183, 63, 685, 8016, 1016, 13563, 31, 203, 3639, 5061, 6433, 273, 272, 18, 9707, 29637, 405, 272, 18, 2135, 29637, 31, 203, 3639, 309, 14015, 3307, 1031, 18, 4963, 24051, 397, 261, 3307, 1031, 18, 4963, 1504, 352, 3719, 380, 261, 72, 330, 1421, 3499, 13, 411, 272, 18, 1896, 5269, 24051, 1876, 1504, 352, 861, 22352, 19338, 13, 288, 203, 5411, 5061, 6433, 273, 629, 31, 203, 3639, 289, 203, 3639, 309, 261, 7640, 63, 685, 8016, 18, 438, 1780, 970, 8009, 78, 1708, 480, 374, 13, 288, 203, 5411, 5061, 6433, 273, 629, 31, 203, 3639, 289, 203, 203, 3639, 327, 5061, 6433, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./open-zeppelin/SafeMath.sol"; import "./KYCRegistrar.sol"; import "./SecurityToken.sol"; import "./Custodian.sol"; import "./components/Modular.sol"; import "./components/MultiSig.sol"; /** @title Issuing Entity */ contract IssuingEntity is Modular, MultiSig { using SafeMath32 for uint32; using SafeMath for uint256; /* Each country can have specific limits for each investor class. minRating corresponds to the minimum investor level for this country. counts[0] and levels[0] == the sum total of counts[1:] and limits[1:] */ struct Country { bool allowed; uint8 minRating; uint32[8] counts; uint32[8] limits; } struct Account { uint192 balance; uint8 rating; uint8 regKey; uint32 custodianCount; bool restricted; mapping (bytes32 => bool) custodians; } struct Token { bool set; bool restricted; } struct Contract { address addr; bool restricted; } bool locked; bool mutex; Contract[] registrars; uint32[8] counts; uint32[8] limits; mapping (uint16 => Country) countries; mapping (bytes32 => Account) accounts; mapping (bytes32 => Contract) custodians; mapping (address => Token) tokens; mapping (string => bytes32) documentHashes; event TransferOwnership( address indexed token, bytes32 indexed from, bytes32 indexed to, uint256 value ); event BeneficialOwnerSet( address indexed custodian, bytes32 indexed id, bool owned ); event CountryModified( uint16 indexed country, bool allowed, uint8 minrating, uint32[8] limits ); event InvestorLimitSet(uint16 indexed country, uint32[8] limits); event NewDocumentHash(string indexed document, bytes32 documentHash); event RegistrarSet(address indexed registrar, bool allowed); event CustodianAdded(address indexed custodian); event TokenAdded(address indexed token); event InvestorRestriction(bytes32 indexed id, bool allowed); event TokenRestriction(address indexed token, bool allowed); event GlobalRestriction(bool allowed); /** @dev check that call originates from a registered, unrestricted token */ modifier onlyToken() { require(tokens[msg.sender].set && !tokens[msg.sender].restricted); _; } /** @notice Issuing entity constructor @param _owners Array of addresses to associate with owner @param _threshold multisig threshold for owning authority */ constructor( address[] _owners, uint32 _threshold ) MultiSig(_owners, _threshold) public { /* First registrar is empty so Account.regKey == 0 means it is unset. */ registrars.push(Contract(0, false)); } /** @notice Fetch balance of an investor from their ID @param _id ID to query @return uint256 balance */ function balanceOf(bytes32 _id) external view returns (uint256) { return uint256(accounts[_id].balance); } /** @notice Fetch total investor counts and limits @return counts, limits */ function getInvestorCounts() external view returns (uint32[8], uint32[8]) { return (counts, limits); } /** @notice Fetch minrating, investor counts and limits of a country @dev counts[0] and levels[0] == the sum of counts[1:] and limits[1:] @param _country Country to query @return uint32 minRating, uint32 arrays of counts, limits */ function getCountry( uint16 _country ) external view returns (uint32 _minRating, uint32[8] _count, uint32[8] _limit) { return ( countries[_country].minRating, countries[_country].counts, countries[_country].limits ); } /** @notice Set all information about a country @param _country Country to modify @param _allowed Is country approved @param _minRating minimum investor rating @param _limits array of investor limits @return bool success */ function setCountry( uint16 _country, bool _allowed, uint8 _minRating, uint32[8] _limits ) external returns (bool) { if (!_checkMultiSig()) return false; Country storage c = countries[_country]; c.limits = _limits; c.minRating = _minRating; c.allowed = _allowed; emit CountryModified(_country, _allowed, _minRating, _limits); return true; } /** @notice Initialize many countries in a single call @dev This call is useful if you have a lot of countries to approve where there is no investor limit specific to the investor ratings @param _country Array of counties to add @param _minRating Array of minimum investor ratings necessary for each country @param _limit Array of maximum mumber of investors allowed from this country @return bool success */ function setCountries( uint16[] _country, uint8[] _minRating, uint32[] _limit ) external returns (bool) { require(_country.length == _minRating.length); require(_country.length == _limit.length); if (!_checkMultiSig()) return false; for (uint256 i = 0; i < _country.length; i++) { require(_minRating[i] != 0); Country storage c = countries[_country[i]]; c.allowed = true; c.minRating = _minRating[i]; c.limits[0] = _limit[i]; emit CountryModified(_country[i], true, _minRating[i], c.limits); } } /** @notice Set investor limits @dev _limits[0] is the total investor limit, [1:] correspond to limits at each specific investor rating. Setting a value of 0 means there is no limit. @param _limits Array of limits @return bool success */ function setInvestorLimits( uint32[8] _limits ) external returns (bool) { if (!_checkMultiSig()) return false; limits = _limits; emit InvestorLimitSet(0, _limits); return true; } /** @notice Check if transfer is possible based on issuer level restrictions @param _token address of token being transferred @param _auth address of the caller attempting the transfer @param _from address of the sender @param _to address of the receiver @param _value number of tokens being transferred @return bytes32 ID of caller @return bytes32[] IDs of sender and receiver @return uint8[] ratings of sender and receiver @return uint16[] countries of sender and receiver */ function checkTransfer( address _token, address _auth, address _from, address _to, uint256 _value ) external returns ( bytes32 _authID, bytes32[2] _id, uint8[2] _rating, uint16[2] _country ) { _authID = _getID(_auth); _id[0] = _getID(_from); _id[1] = _getID(_to); if (_authID == ownerID && idMap[_auth].id != ownerID) { /* bytes4 signatures of transfer, transferFrom This enforces sub-authority permissioning around transfers */ require( authorityData[idMap[_auth].id].approvedUntil >= now && authorityData[idMap[_auth].id].signatures[ (_authID == _id[0] ? bytes4(0xa9059cbb) : bytes4(0x23b872dd)) ], "Authority is not permitted" ); } address _addr = (_authID == _id[0] ? _auth : _from); bool[2] memory _allowed; (_allowed, _rating, _country) = _getInvestors( [_addr, _to], [accounts[idMap[_addr].id].regKey, accounts[idMap[_to].id].regKey] ); _checkTransfer(_token, _authID, _id, _allowed, _rating, _country, _value); return (_authID, _id, _rating, _country); } /** @notice View function to check if transfer is permitted @param _token address of token being transferred @param _from address of the sender @param _to address of the receiver @param _value number of tokens being transferred @return bytes32[] IDs of sender and receiver @return uint8[] ratings of sender and receiver @return uint16[] countries of sender and receiver */ function checkTransferView( address _token, address _from, address _to, uint256 _value ) external view returns ( bytes32[2] _id, uint8[2] _rating, uint16[2] _country ) { uint8[2] memory _key; (_id[0], _key[0]) = _getIDView(_from); (_id[1], _key[1]) = _getIDView(_to); if (_id[0] == ownerID && idMap[_from].id != ownerID) { require( authorityData[idMap[_from].id].approvedUntil >= now && authorityData[idMap[_from].id].signatures[0xa9059cbb], "Authority is not permitted" ); } address[2] memory _addr = [_from, _to]; bool[2] memory _allowed; (_allowed, _rating, _country) = _getInvestors(_addr, _key); _checkTransfer(_token, _id[0], _id, _allowed, _rating, _country, _value); return (_id, _rating, _country); } /** @notice internal check if transfer is permitted @param _token address of token being transferred @param _authID id hash of caller @param _id addresses of sender and receiver @param _allowed array of permission bools from registrar @param _rating array of investor ratings @param _country array of investor countries @param _value amount to be transferred */ function _checkTransfer( address _token, bytes32 _authID, bytes32[2] _id, bool[2] _allowed, uint8[2] _rating, uint16[2] _country, uint256 _value ) internal view { require(tokens[_token].set); /* If issuer is not the authority, check the sender is not restricted */ if (_authID != ownerID) { require(!locked, "Transfers locked: Issuer"); require(!tokens[_token].restricted, "Transfers locked: Token"); require(!accounts[_id[0]].restricted, "Sender restricted: Issuer"); require(_allowed[0], "Sender restricted: Registrar"); } /* Always check the receiver is not restricted. */ require(!accounts[_id[1]].restricted, "Receiver restricted: Issuer"); require(_allowed[1], "Receiver restricted: Registrar"); if (_id[0] != _id[1]) { /* A rating of 0 implies the receiver is the issuer or a custodian, no further checks are needed. */ if (_rating[1] != 0) { Country storage c = countries[_country[1]]; require(c.allowed, "Reciever blocked: Country"); /* If the receiving investor currently has a 0 balance, we must make sure a slot is available for allocation. */ require(_rating[1] >= c.minRating, "Receiver blocked: Rating"); if (accounts[_id[1]].balance == 0) { /* create a bool to prevent repeated comparisons */ bool _check = ( _rating[0] != 0 || accounts[_id[1]].balance > _value ); /* If the sender is an investor and still retains a balance, a new slot must be available. */ if (_check) { require( limits[0] == 0 || counts[0] < limits[0], "Total Investor Limit" ); } /* If the investors are from different countries, make sure a slot is available in the overall country limit. */ if (_check || _country[0] != _country[1]) { require( c.limits[0] == 0 || c.counts[0] < c.limits[0], "Country Investor Limit" ); } if (!_check) { _check = _rating[0] != _rating[1]; } /* If the investors are of different ratings, make sure a slot is available in the receiver's rating in the overall count. */ if (_check) { require( limits[_rating[1]] == 0 || counts[_rating[1]] < limits[_rating[1]], "Total Investor Limit: Rating" ); } /* If the investors don't match in country or rating, make sure a slot is available in both the specific country and rating for the receiver. */ if (_check || _country[0] != _country[1]) { require( c.limits[_rating[1]] == 0 || c.counts[_rating[1]] < c.limits[_rating[1]], "Country Investor Limit: Rating" ); } } } } /* bytes4 signature for issuer module checkTransfer() */ _callModules(0x47fca5df, abi.encode( _token, _authID, _id, _rating, _country, _value )); } /** @notice External view to fetch an investor ID from an address @param _addr address of token being transferred @return bytes32 investor ID */ function getID(address _addr) external view returns (bytes32) { (bytes32 _id, uint8 _key) = _getIDView(_addr); return _id; } /** @notice internal investor ID fetch, updates local record @param _addr address of token being transferred @return bytes32 investor ID */ function _getID(address _addr) internal returns (bytes32) { (bytes32 _id, uint8 _key) = _getIDView(_addr); if (idMap[_addr].id == 0) { idMap[_addr].id = _id; } if (accounts[_id].regKey != _key) { accounts[_id].regKey = _key; } return _id; } /** @notice internal investor ID fetch @dev common logic for getID() and _getID() @param _addr address of token being transferred @return bytes32 investor ID, uint8 registrar index */ function _getIDView(address _addr) internal view returns (bytes32, uint8) { if ( authorityData[idMap[_addr].id].addressCount > 0 || _addr == address(this) ) { return (ownerID, 0); } bytes32 _id = idMap[_addr].id; if (_id == 0) { for (uint256 i = 1; i < registrars.length; i++) { if (!registrars[i].restricted) { _id = KYCRegistrar(registrars[i].addr).getID(_addr); if (_id != 0) { return (_id, uint8(i)); } } } revert("Address not registered"); } if (custodians[_id].addr != 0) { return (_id, 0); } if ( accounts[_id].regKey == 0 || registrars[accounts[_id].regKey].restricted ) { for (i = 1; i < registrars.length; i++) { if ( !registrars[i].restricted && _id == KYCRegistrar(registrars[i].addr).getID(_addr) ) { return (_id, uint8(i)); } } if (registrars[accounts[_id].regKey].restricted) { revert("Registrar restricted"); } revert("Address not registered"); } return (_id, accounts[_id].regKey); } /** @dev fetch investor data from registrar(s) @param _addr array of investor addresses @param _key array of registrar indexes @return permissions, ratings, and countries of investors */ function _getInvestors( address[2] _addr, uint8[2] _key ) internal view returns ( bool[2] _allowed, uint8[2] _rating, uint16[2] _country ) { bytes32[2] memory _id; /* If key == 0 the address belongs to the issuer or a custodian. */ if (_key[0] == 0) { _allowed[0] = true; _rating[0] = 0; _country[0] = 0; } if (_key[1] == 0) { _allowed[1] = true; _rating[1] = 0; _country[1] = 0; } /* If both investors are in the same registry, call getInvestors */ if (_key[0] == _key[1] && _key[0] != 0) { ( _id, _allowed, _rating, _country ) = KYCRegistrar(registrars[_key[0]].addr).getInvestors(_addr[0], _addr[1]); /* Otherwise, call getInvestor at each registry */ } else { if (_key[0] != 0) { ( _id[0], _allowed[0], _rating[0], _country[0] ) = KYCRegistrar(registrars[_key[0]].addr).getInvestor(_addr[0]); } if (_key[1] != 0) { ( _id[1], _allowed[1], _rating[1], _country[1] ) = KYCRegistrar(registrars[_key[1]].addr).getInvestor(_addr[1]); } } return (_allowed, _rating, _country); } /** @notice Transfer tokens through the issuing entity level @param _id Array of sender/receiver IDs @param _rating Array of sender/receiver ratings @param _country Array of sender/receiver countries @param _value Number of tokens being transferred @return bool success */ function transferTokens( bytes32[2] _id, uint8[2] _rating, uint16[2] _country, uint256 _value ) external onlyToken returns (bool) { /* custodian re-entrancy guard */ require (!mutex); /* If no transfer of ownership, return true immediately */ if (_id[0] == _id[1]) return true; /* If receiver is a custodian and sender is an investor, notify the custodian contract. */ if (custodians[_id[1]].addr != 0) { Custodian c = Custodian(custodians[_id[1]].addr); mutex = true; if (c.receiveTransfer(msg.sender, _id[0], _value) && _rating[0] > 0) { accounts[_id[0]].custodianCount = accounts[_id[0]].custodianCount.add(1); accounts[_id[0]].custodians[_id[1]] = true; emit BeneficialOwnerSet(address(c), _id[0], true); } mutex = false; } uint256 _balance = uint256(accounts[_id[0]].balance).sub(_value); _setBalance(_id[0], _rating[0], _country[0], _balance); _balance = uint256(accounts[_id[1]].balance).add(_value); _setBalance(_id[1], _rating[1], _country[1], _balance); /* bytes4 signature for token module transferTokens() */ _callModules(0x0cfb54c9, abi.encode( msg.sender, _id, _rating, _country, _value )); emit TransferOwnership(msg.sender, _id[0], _id[1], _value); return true; } /** @notice Affect a direct balance change (burn/mint) at the issuing entity level @dev This can only be called by a token @param _owner Token owner @param _old Old balance @param _new New balance @return id, rating, and country of the affected investor */ function modifyBalance( address _owner, uint256 _old, uint256 _new ) external onlyToken returns ( bytes32 _id, uint8 _rating, uint16 _country ) { if (_owner == address(this)) { _id = ownerID; _rating = 0; _country = 0; } else { bool _allowed; uint8 _key = accounts[idMap[_owner].id].regKey; ( _id, _allowed, _rating, _country ) = KYCRegistrar(registrars[_key].addr).getInvestor(_owner); } uint256 _oldTotal = accounts[_id].balance; if (_new > _old) { uint256 _newTotal = uint256(accounts[_id].balance).add(_new.sub(_old)); } else { _newTotal = uint256(accounts[_id].balance).sub(_old.sub(_new)); } _setBalance(_id, _rating, _country, _newTotal); /* bytes4 signature for token module balanceChanged() */ _callModules(0x4268353d, abi.encode( msg.sender, _id, _rating, _country, _oldTotal, _newTotal )); return (_id, _rating, _country); } /** @notice Directly set a balance at the issuing entity level @param _id investor ID @param _rating investor rating @param _country investor country @param _value new balance value */ function _setBalance( bytes32 _id, uint8 _rating, uint16 _country, uint256 _value ) internal { Account storage a = accounts[_id]; Country storage c = countries[_country]; if (_rating != 0) { /* rating from registrar does not match local rating */ if (_rating != a.rating) { /* if local rating is not 0, rating has changed */ if (a.rating > 0) { c.counts[_rating] = c.counts[_rating].sub(1); c.counts[a.rating] = c.counts[a.rating].add(1); } a.rating = _rating; } /* If investor account balance was 0, increase investor counts */ if (a.balance == 0 && accounts[_id].custodianCount == 0) { _incrementCount(_rating, _country); /* If investor account balance is now 0, reduce investor counts */ } else if (_value == 0 && accounts[_id].custodianCount == 0) { _decrementCount(_rating, _country); } } a.balance = uint192(_value); require(a.balance == _value); } /** @notice Increment investor count @param _r Investor rating @param _c Investor country @return bool success */ function _incrementCount(uint8 _r, uint16 _c) internal { counts[0] = counts[0].add(1); counts[_r] = counts[_r].add(1); countries[_c].counts[0] = countries[_c].counts[0].add(1); countries[_c].counts[_r] = countries[_c].counts[_r].add(1); } /** @notice Decrement investor count @param _r Investor rating @param _c Investor country @return bool success */ function _decrementCount(uint8 _r, uint16 _c) internal { counts[0] = counts[0].sub(1); counts[_r] = counts[_r].sub(1); countries[_c].counts[0] = countries[_c].counts[0].sub(1); countries[_c].counts[_r] = countries[_c].counts[_r].sub(1); } /** @notice Set document hash @param _documentID Document ID being hashed @param _hash Hash of the document @return bool success */ function setDocumentHash( string _documentID, bytes32 _hash ) external returns (bool) { if (!_checkMultiSig()) return false; require(documentHashes[_documentID] == 0); documentHashes[_documentID] = _hash; emit NewDocumentHash(_documentID, _hash); return true; } /** @notice Fetch document hash @param _documentID Document ID to fetch @return document hash */ function getDocumentHash(string _documentID) external view returns (bytes32) { return documentHashes[_documentID]; } /** @notice Attach or remove a KYCRegistrar contract @param _registrar address of registrar @param _allowed registrar permission @return bool success */ function setRegistrar(address _registrar, bool _allowed) external returns (bool) { if (!_checkMultiSig()) return false; for (uint256 i = 1; i < registrars.length; i++) { if (registrars[i].addr == _registrar) { registrars[i].restricted = !_allowed; emit RegistrarSet(_registrar, _allowed); return true; } } if (_allowed) { registrars.push(Contract(_registrar, false)); emit RegistrarSet(_registrar, _allowed); return true; } revert(); } /** @notice Get address of the registrar an investor is associated with @param _id Investor ID @return registrar address */ function getInvestorRegistrar(bytes32 _id) external view returns (address) { return registrars[accounts[_id].regKey].addr; } /** @notice Add a custodian @dev Custodians are entities such as broker or exchanges that are approved to hold tokens for 1 or more beneficial owners. https://sft-protocol.readthedocs.io/en/latest/custodian.html @param _custodian address of custodian contract @return bool success */ function addCustodian(address _custodian) external returns (bool) { if (!_checkMultiSig()) return false; bytes32 _id = Custodian(_custodian).ownerID(); idMap[_custodian].id = _id; custodians[_id].addr = _custodian; emit CustodianAdded(_custodian); return true; } /** @notice Add a new security token contract @param _token Token contract address @return bool success */ function addToken(address _token) external returns (bool) { if (!_checkMultiSig()) return false; SecurityToken token = SecurityToken(_token); require(!tokens[_token].set); require(token.ownerID() == ownerID); require(token.circulatingSupply() == 0); tokens[_token].set = true; uint256 _balance = uint256(accounts[ownerID].balance).add(token.treasurySupply()); accounts[ownerID].balance = uint192(_balance); require(accounts[ownerID].balance == _balance); emit TokenAdded(_token); return true; } /** @notice Set restriction on an investor ID @dev This is used for regular investors or custodians. Restrictions on sub-authorities must be handled with MultiSig functions. @param _id investor ID @param _allowed permission bool @return bool success */ function setInvestorRestriction( bytes32 _id, bool _allowed ) external returns (bool) { if (!_checkMultiSig()) return false; accounts[_id].restricted = !_allowed; emit InvestorRestriction(_id, _allowed); return true; } /** @notice Set restriction on a token @dev Only the issuer can transfer restricted tokens. Useful in dealing with a security breach or a token migration. @param _token Address of the token @param _allowed permission bool @return bool success */ function setTokenRestriction( address _token, bool _allowed ) external returns (bool) { if (!_checkMultiSig()) return false; require(tokens[_token].set); tokens[_token].restricted = !_allowed; emit TokenRestriction(_token, _allowed); return true; } /** @notice Set restriction on all tokens for this issuer @dev Only the issuer can transfer restricted tokens. @param _allowed permission bool @return bool success */ function setGlobalRestriction(bool _allowed) external returns (bool) { if (!_checkMultiSig()) return false; locked = !_allowed; emit GlobalRestriction(_allowed); return true; } /** @notice Attach a module to IssuingEntity or SecurityToken @dev Modules have a lot of permission and flexibility in what they can do. Only attach a module that has been properly auditted and where you understand exactly what it is doing. https://sft-protocol.readthedocs.io/en/latest/modules.html @param _target Address of the contract where the module is attached @param _module Address of the module contract @return bool success */ function attachModule( address _target, address _module ) external returns (bool) { if (!_checkMultiSig()) return false; if (_target == address(this)) { _attachModule(_module); } else { require(tokens[_target].set); SecurityToken(_target).attachModule(_module); } return true; } /** @notice Detach a module from IssuingEntity or SecurityToken @dev This function may also be called by the module itself. @param _target Address of the contract where the module is attached @param _module Address of the module contract @return bool success */ function detachModule( address _target, address _module ) external returns (bool) { if (_module != msg.sender) { if (!_checkMultiSig()) return false; } if (_target == address(this)) { _detachModule(_module); } else { require(tokens[_target].set); SecurityToken(_target).detachModule(_module); } return true; } /** @notice Add or remove an investor from a custodian's beneficial owners @dev Only callable by a custodian or the issuer @param _custID Custodian ID @param _id Array of investor IDs @param _add bool add or remove @return bool success */ function setBeneficialOwners( bytes32 _custID, bytes32[] _id, bool _add ) external returns (bool) { /* custodian re-entrancy guard */ require (!mutex); if (custodians[_custID].addr != msg.sender) { if (!_checkMultiSig()) return false; } for (uint256 i = 0; i < _id.length; i++) { if (_id[i] == 0) continue; if (_id[i] == ownerID || custodians[_id[i]].addr != 0) continue; Account storage a = accounts[_id[i]]; if (a.custodians[_custID] == _add) continue; a.custodians[_custID] = _add; emit BeneficialOwnerSet(msg.sender, _id[i], _add); if (_add) { a.custodianCount = a.custodianCount.add(1); if (a.custodianCount == 1 && a.balance == 0) { _incrementCount( a.rating, KYCRegistrar(registrars[a.regKey].addr).getCountry(_id[i]) ); } } else { a.custodianCount = a.custodianCount.sub(1); if (a.custodianCount == 0 && a.balance == 0) { _decrementCount( a.rating, KYCRegistrar(registrars[a.regKey].addr).getCountry(_id[i]) ); } } } return true; } }
/ custodian re-entrancy guard */
function setBeneficialOwners( bytes32 _custID, bytes32[] _id, bool _add ) external returns (bool) { require (!mutex); if (custodians[_custID].addr != msg.sender) { if (!_checkMultiSig()) return false; } for (uint256 i = 0; i < _id.length; i++) { if (_id[i] == 0) continue; if (_id[i] == ownerID || custodians[_id[i]].addr != 0) continue; Account storage a = accounts[_id[i]]; if (a.custodians[_custID] == _add) continue; a.custodians[_custID] = _add; emit BeneficialOwnerSet(msg.sender, _id[i], _add); if (_add) { a.custodianCount = a.custodianCount.add(1); if (a.custodianCount == 1 && a.balance == 0) { _incrementCount( a.rating, KYCRegistrar(registrars[a.regKey].addr).getCountry(_id[i]) ); } a.custodianCount = a.custodianCount.sub(1); if (a.custodianCount == 0 && a.balance == 0) { _decrementCount( a.rating, KYCRegistrar(registrars[a.regKey].addr).getCountry(_id[i]) ); } } } return true; }
14,076,334
[ 1, 19, 276, 641, 369, 2779, 283, 17, 8230, 12514, 11026, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 15268, 4009, 74, 22354, 5460, 414, 12, 203, 202, 202, 3890, 1578, 389, 71, 641, 734, 16, 203, 202, 202, 3890, 1578, 8526, 389, 350, 16, 203, 202, 202, 6430, 389, 1289, 203, 202, 13, 203, 202, 202, 9375, 203, 202, 202, 6154, 261, 6430, 13, 203, 202, 95, 203, 202, 202, 6528, 16051, 29946, 1769, 203, 202, 202, 430, 261, 71, 641, 369, 19657, 63, 67, 71, 641, 734, 8009, 4793, 480, 1234, 18, 15330, 13, 288, 203, 1082, 202, 430, 16051, 67, 1893, 5002, 8267, 10756, 327, 629, 31, 203, 202, 202, 97, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 350, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 430, 261, 67, 350, 63, 77, 65, 422, 374, 13, 1324, 31, 203, 1082, 202, 430, 261, 67, 350, 63, 77, 65, 422, 3410, 734, 747, 276, 641, 369, 19657, 63, 67, 350, 63, 77, 65, 8009, 4793, 480, 374, 13, 1324, 31, 203, 1082, 202, 3032, 2502, 279, 273, 9484, 63, 67, 350, 63, 77, 13563, 31, 203, 1082, 202, 430, 261, 69, 18, 71, 641, 369, 19657, 63, 67, 71, 641, 734, 65, 422, 389, 1289, 13, 1324, 31, 203, 1082, 202, 69, 18, 71, 641, 369, 19657, 63, 67, 71, 641, 734, 65, 273, 389, 1289, 31, 203, 1082, 202, 18356, 605, 4009, 74, 22354, 5541, 694, 12, 3576, 18, 15330, 16, 389, 350, 63, 77, 6487, 389, 1289, 1769, 203, 1082, 202, 430, 261, 67, 1289, 13, 288, 203, 2 ]
pragma solidity 0.5.8; /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.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 msg.sender == _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; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ 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, "ReentrancyGuard: reentrant call"); } } 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; } /// @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); } /** * @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. * * > 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); } /** * @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 that 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 Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in 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; } } /** * @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); 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"); } } } /** * @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); } /** * @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 DAI_ADDR; address payable public KYBER_ADDR; bytes public constant PERM_HINT = "PERM"; ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal dai; KyberNetwork internal kyber; uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal ETH_DECIMALS = 18; uint constant internal MAX_DECIMALS = 18; constructor( address _daiAddr, address payable _kyberAddr ) public { DAI_ADDR = _daiAddr; KYBER_ADDR = _kyberAddr; dai = ERC20Detailed(_daiAddr); 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(uint srcAmount, uint destAmount, uint srcDecimals, uint 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); // Get current rate & ensure token is listed on Kyber (, uint256 rate) = kyber.getExpectedRate(_srcToken, _destToken, _srcAmount); require(rate > 0); 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, rate, 0x332D87209f7c8296389C307eAe170c2440830A47, PERM_HINT ); require(_actualDestAmount > 0); if (_srcToken != ETH_TOKEN_ADDRESS) { _srcToken.safeApprove(KYBER_ADDR, 0); } _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); _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) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) pure internal returns (address payable) { return address(uint160(_addr)); } } interface BetokenProxyInterface { function betokenFundAddress() external view returns (address payable); function updateBetokenFundAddress() external; } /** * @title The storage layout of BetokenFund * @author Zefram Lou (Zebang Liu) */ contract BetokenStorage 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 DAI uint256 sellPrice; // token sell price in 18 decimals in DAI uint256 buyTime; uint256 buyCostInDAI; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 20 * (10 ** 16); // The proportion of profits that gets distributed to Kairo holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10 ** 15); // The proportion of fund balance that gets distributed to Kairo holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10 ** 18); // Amount of Kairo rewarded to the user who calls nextPhase(). uint256 public constant MAX_BUY_KRO_PROP = 1 * (10 ** 16); // max Kairo you can buy is 1% of total supply uint256 public constant FALLBACK_MAX_DONATION = 100 * (10 ** 18); // If payment cap for registration is below 100 DAI, use 100 DAI instead uint256 public constant MIN_KRO_PRICE = 25 * (10 ** 17); // 1 KRO >= 2.5 DAI uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10 ** 16); // Modifies Compound's collateral ratio, gets 2:1 ratio from current 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * kairoBalance uint256 public constant INACTIVE_THRESHOLD = 6; // Number of inactive cycles after which a manager's Kairo balance can be burned // Upgrade constants uint256 public constant CHUNK_SIZE = 3 days; uint256 public constant PROPOSE_SUBCHUNK_SIZE = 1 days; uint256 public constant CYCLES_TILL_MATURITY = 3; uint256 public constant QUORUM = 10 * (10 ** 16); // 10% quorum uint256 public constant VOTE_SUCCESS_THRESHOLD = 75 * (10 ** 16); // Votes on upgrade candidates need >75% voting weight to pass // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Address of the Kairo token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the BetokenProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the BetokenLogic contract. address public betokenLogic; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of BetokenFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInDAI; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of Betoken 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 last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) public lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) public hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) public riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) public 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) public totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) public managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) public 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 cDAI and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // Check if an address points to a whitelisted Fulcrum position token. mapping(address => bool) public isPositionToken; // 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 bool public upgradeVotingActive; // Denotes if the vote for which contract to upgrade to is active address payable public nextVersion; // Address of the next version of BetokenFund. address[5] public proposers; // Manager who proposed the upgrade candidate in a chunk address payable[5] public candidates; // Candidates for a chunk uint256[5] public forVotes; // For votes for a chunk uint256[5] public againstVotes; // Against votes for a chunk uint256 public proposersVotingWeight; // Total voting weight of previous and current proposers. This is used for excluding the voting weight of proposers. mapping(uint256 => mapping(address => VoteDirection[5])) public managerVotes; // Records each manager's vote mapping(uint256 => uint256) public upgradeSignalStrength; // Denotes the amount of Kairo that's signalling in support of beginning the upgrade process during a cycle mapping(uint256 => mapping(address => bool)) public upgradeSignal; // Maps manager address to whether they support initiating an upgrade // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; BetokenProxyInterface internal proxy; // Events event ChangedPhase(uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInDAI); event Deposit(uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _daiAmount, uint256 _timestamp); event Withdraw(uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _daiAmount, uint256 _timestamp); event CreatedInvestment(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costDAIAmount, uint256 _tokenAmount); event SoldInvestment(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedKairo, uint256 _sellPrice, uint256 _earnedDAIAmount); event CreatedCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costDAIAmount); event SoldCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedKairo, uint256 _earnedDAIAmount); event RepaidCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidDAIAmount); event CommissionPaid(uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission); event TotalCommissionPaid(uint256 indexed _cycleNumber, uint256 _totalCommissionInDAI); event Register(address indexed _manager, uint256 _donationInDAI, uint256 _kairoReceived); event SignaledUpgrade(uint256 indexed _cycleNumber, address indexed _sender, bool indexed _inSupport); event DeveloperInitiatedUpgrade(uint256 indexed _cycleNumber, address _candidate); event InitiatedUpgrade(uint256 indexed _cycleNumber); event ProposedCandidate(uint256 indexed _cycleNumber, uint256 indexed _voteID, address indexed _sender, address _candidate); event Voted(uint256 indexed _cycleNumber, uint256 indexed _voteID, address indexed _sender, bool _inSupport, uint256 _weight); event FinalizedNextVersion(uint256 indexed _cycleNumber, address _nextVersion); /* Helper functions shared by both BetokenLogic & BetokenFund */ /** * @notice The manage phase is divided into 9 3-day chunks. Determines which chunk the fund's in right now. * @return The index of the current chunk (starts from 0). Returns 0 if not in Manage phase. */ function currentChunk() public view returns (uint) { if (cyclePhase != CyclePhase.Manage) { return 0; } return (now - startTimeOfCyclePhase) / CHUNK_SIZE; } /** * @notice There are two subchunks in each chunk: propose (1 day) and vote (2 days). * Determines which subchunk the fund is in right now. * @return The Subchunk the fund is in right now */ function currentSubchunk() public view returns (Subchunk _subchunk) { if (cyclePhase != CyclePhase.Manage) { return Subchunk.Vote; } uint256 timeIntoCurrChunk = (now - startTimeOfCyclePhase) % CHUNK_SIZE; return timeIntoCurrChunk < PROPOSE_SUBCHUNK_SIZE ? Subchunk.Propose : Subchunk.Vote; } /** * @notice Calculates an account's voting weight based on their Kairo balance * 3 cycles ago * @param _of the account to be queried * @return The account's voting weight */ function getVotingWeight(address _of) public view returns (uint256 _weight) { if (cycleNumber <= CYCLES_TILL_MATURITY || _of == address(0)) { return 0; } return cToken.balanceOfAt(_of, managePhaseEndBlock[cycleNumber.sub(CYCLES_TILL_MATURITY)]); } /** * @notice Calculates the total voting weight based on the total Kairo supply * 3 cycles ago. The weights of proposers are deducted. * @return The total voting weight right now */ function getTotalVotingWeight() public view returns (uint256 _weight) { if (cycleNumber <= CYCLES_TILL_MATURITY) { return 0; } return cToken.totalSupplyAt(managePhaseEndBlock[cycleNumber.sub(CYCLES_TILL_MATURITY)]).sub(proposersVotingWeight); } /** * @notice Calculates the current price of Kairo. The price is equal to the amount of DAI each Kairo * can control, and it's kept above MIN_KRO_PRICE. * @return Kairo's current price */ function kairoPrice() public view returns (uint256 _kairoPrice) { if (cToken.totalSupply() == 0) { return MIN_KRO_PRICE; } uint256 controlPerKairo = totalFundsInDAI.mul(10 ** 18).div(cToken.totalSupply()); if (controlPerKairo < MIN_KRO_PRICE) { // keep price above minimum price return MIN_KRO_PRICE; } return controlPerKairo; } } // 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); } // Compound finance's price oracle interface PriceOracle { function getPrice(address asset) external view returns (uint); } // 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); } contract CompoundOrderStorage is Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 10 ** 14; // we don't care about debts below 10^-4 DAI (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CDAI; // The Compound DAI market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInDAI; uint256 public loanAmountInDAI; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output DAI after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing // The contract containing the code to be executed address public logicContract; } contract CompoundOrder is CompoundOrderStorage, Utils { constructor( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInDAI, uint256 _loanAmountInDAI, bool _orderType, address _logicContract, address _daiAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cDAIAddr, address _cETHAddr ) public Utils(_daiAddr, _kyberAddr) { // Initialize details of short order require(_compoundTokenAddr != _cDAIAddr); require(_stake > 0 && _collateralAmountInDAI > 0 && _loanAmountInDAI > 0); // Validate inputs stake = _stake; collateralAmountInDAI = _collateralAmountInDAI; loanAmountInDAI = _loanAmountInDAI; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; logicContract = _logicContract; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CDAI = CERC20(_cDAIAddr); CETH_ADDR = _cETHAddr; } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public { (bool success,) = logicContract.delegatecall(abi.encodeWithSelector(this.executeOrder.selector, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Sells the Compound order and returns assets to BetokenFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.sellOrder.selector, _minPrice, _maxPrice)); if (!success) { revert(); } return abi.decode(result, (uint256, uint256)); } /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInDAI the amount to repay, in DAI */ function repayLoan(uint256 _repayAmountInDAI) public { (bool success,) = logicContract.delegatecall(abi.encodeWithSelector(this.repayLoan.selector, _repayAmountInDAI)); if (!success) { revert(); } } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInDAI() public returns (bool _isNegative, uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentLiquidityInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (bool, uint256)); } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCollateralRatioInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } /** * @notice Calculates the current profit in DAI * @return the profit amount */ function getCurrentProfitInDAI() public returns (bool _isNegative, uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentProfitInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (bool, uint256)); } function getMarketCollateralFactor() public returns (uint256) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getMarketCollateralFactor.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentCollateralInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCollateralInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentBorrowInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentBorrowInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentCashInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCashInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function() external payable {} } contract CompoundOrderFactory { 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 DAI_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CDAI_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _daiAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cDAIAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; DAI_ADDR = _daiAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CDAI_ADDR = _cDAIAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInDAI, uint256 _loanAmountInDAI, bool _orderType ) public returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address logicContract; if (_compoundTokenAddr != CETH_ADDR) { logicContract = _orderType ? SHORT_CERC20_LOGIC_CONTRACT : LONG_CERC20_LOGIC_CONTRACT; } else { logicContract = _orderType ? SHORT_CEther_LOGIC_CONTRACT : LONG_CEther_LOGIC_CONTRACT; } order = new CompoundOrder(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInDAI, _loanAmountInDAI, _orderType, logicContract, DAI_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CDAI_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) public view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } } /** * @title The main smart contract of the Betoken hedge fund. * @author Zefram Lou (Zebang Liu) */ contract BetokenFund is BetokenStorage, Utils, TokenController { /** * @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); _; } /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require(now > startTimeOfCyclePhase.add(phaseLengths[uint(CyclePhase.Intermission)])); _; } /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * Meta functions */ constructor( address payable _kroAddr, address payable _sTokenAddr, address payable _devFundingAccount, uint256[2] memory _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _daiAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _betokenLogic ) public Utils(_daiAddr, _kyberAddr) { controlTokenAddr = _kroAddr; shareTokenAddr = _sTokenAddr; devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Manage; compoundFactoryAddr = _compoundFactoryAddr; betokenLogic = _betokenLogic; previousVersion = _previousVersion; cToken = IMiniMeToken(_kroAddr); sToken = IMiniMeToken(_sTokenAddr); } function initTokenListings( address[] memory _kyberTokens, address[] memory _compoundTokens, address[] memory _positionTokens ) public onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i = i.add(1)) { isKyberToken[_kyberTokens[i]] = true; } for (i = 0; i < _compoundTokens.length; i = i.add(1)) { isCompoundToken[_compoundTokens[i]] = true; } for (i = 0; i < _positionTokens.length; i = i.add(1)) { isPositionToken[_positionTokens[i]] = true; } } /** * @notice Used during deployment to set the BetokenProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) public onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = BetokenProxyInterface(_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 during(CyclePhase.Intermission) onlyOwner notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.developerInitiateUpgrade.selector, _candidate)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows a manager to signal their support of initiating an upgrade. They can change their signal before the end of the Intermission phase. * Managers who oppose initiating an upgrade don't need to call this function, unless they origianlly signalled in support. * Signals are reset every cycle. * @param _inSupport True if the manager supports initiating upgrade, false if the manager opposes it. * @return True if successfully changed signal, false if no changes were made. */ function signalUpgrade(bool _inSupport) public during(CyclePhase.Intermission) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.signalUpgrade.selector, _inSupport)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows manager to propose a candidate smart contract for the fund to upgrade to. Among the managers who have proposed a candidate, * the manager with the most voting weight's candidate will be used in the vote. Ties are broken in favor of the larger address. * The proposer may change the candidate they support during the Propose subchunk in their chunk. * @param _chunkNumber the chunk for which the sender is proposing the candidate * @param _candidate the address of the candidate smart contract * @return True if successfully proposed/changed candidate, false otherwise. */ function proposeCandidate(uint256 _chunkNumber, address payable _candidate) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.proposeCandidate.selector, _chunkNumber, _candidate)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows a manager to vote for or against a candidate smart contract the fund will upgrade to. The manager may change their vote during * the Vote subchunk. A manager who has been a proposer may not vote. * @param _inSupport True if the manager supports initiating upgrade, false if the manager opposes it. * @return True if successfully changed vote, false otherwise. */ function voteOnCandidate(uint256 _chunkNumber, bool _inSupport) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.voteOnCandidate.selector, _chunkNumber, _inSupport)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Performs the necessary state changes after a successful vote * @param _chunkNumber the chunk number of the successful vote * @return True if successful, false otherwise */ function finalizeSuccessfulVote(uint256 _chunkNumber) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.finalizeSuccessfulVote.selector, _chunkNumber)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of Kairo & Share token contracts to the next version. Also updates BetokenFund's * address in BetokenProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); proxy.updateBetokenFundAddress(); } /** * @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 DAI */ 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 = cycle.add(1)) { (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 DAI */ 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 baseKairoBalance = cToken.balanceOfAt(_manager, managePhaseEndBlock[_cycle.sub(1)]); uint256 baseStake = baseKairoBalance == 0 ? baseRiskStakeFallback[_manager] : baseKairoBalance; if (baseKairoBalance == 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); } /** * 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 Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.nextPhase.selector)); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using DAI as payment. The more one pays, the more Kairo one gets. * There's a max Kairo amount that can be bought, and excess payment will be sent back to sender. * @param _donationInDAI the amount of DAI to be used for registration */ function registerWithDAI(uint256 _donationInDAI) public nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.registerWithDAI.selector, _donationInDAI)); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more Kairo one gets. * There's a max Kairo amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable nonReentrant { (bool success,) = betokenLogic.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 Kairo one gets. * There's a max Kairo 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 nonReentrant { (bool success,) = betokenLogic.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 DAI. */ function depositEther() public payable during(CyclePhase.Intermission) nonReentrant notReadyForUpgrade { // Buy DAI with ETH uint256 actualDAIDeposited; uint256 actualETHDeposited; (,, actualDAIDeposited, actualETHDeposited) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, dai); // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualDAIDeposited); // Emit event emit Deposit(cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualDAIDeposited, now); } /** * @notice Deposit DAI Stablecoin into the fund. * @param _daiAmount The amount of DAI to be deposited. May be different from actual deposited amount. */ function depositDAI(uint256 _daiAmount) public during(CyclePhase.Intermission) nonReentrant notReadyForUpgrade { dai.safeTransferFrom(msg.sender, address(this), _daiAmount); // Register investment __deposit(_daiAmount); // Emit event emit Deposit(cycleNumber, msg.sender, DAI_ADDR, _daiAmount, _daiAmount, now); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into DAI. * @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) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) notReadyForUpgrade { require(_tokenAddr != DAI_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into DAI uint256 actualDAIDeposited; uint256 actualTokenDeposited; (,, actualDAIDeposited, actualTokenDeposited) = __kyberTrade(token, _tokenAmount, dai); // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualDAIDeposited); // Emit event emit Deposit(cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualDAIDeposited, now); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInDAI Amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInDAI) public during(CyclePhase.Intermission) nonReentrant { // Buy ETH uint256 actualETHWithdrawn; uint256 actualDAIWithdrawn; (,, actualETHWithdrawn, actualDAIWithdrawn) = __kyberTrade(dai, _amountInDAI, ETH_TOKEN_ADDRESS); __withdraw(actualDAIWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw(cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualDAIWithdrawn, now); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInDAI Amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawDAI(uint256 _amountInDAI) public during(CyclePhase.Intermission) nonReentrant { __withdraw(_amountInDAI); // Transfer DAI to user dai.safeTransfer(msg.sender, _amountInDAI); // Emit event emit Withdraw(cycleNumber, msg.sender, DAI_ADDR, _amountInDAI, _amountInDAI, now); } /** * @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 _amountInDAI The amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInDAI) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) { require(_tokenAddr != DAI_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert DAI into desired tokens uint256 actualTokenWithdrawn; uint256 actualDAIWithdrawn; (,, actualTokenWithdrawn, actualDAIWithdrawn) = __kyberTrade(dai, _amountInDAI, token); __withdraw(actualDAIWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw(cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualDAIWithdrawn, now); } /** * @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, DAI_ADDR, commission, commission, now); } else { // Transfer the commission in DAI dai.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in Betoken Shares, false to redeem in DAI * @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, DAI_ADDR, commission, commission, now); } else { // Transfer the commission in DAI dai.safeTransfer(msg.sender, commission); } } /** * @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 */ function sellLeftoverToken(address _tokenAddr) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (,,uint256 actualDAIReceived,) = __kyberTrade(token, getBalance(token, address(this)), dai); totalFundsInDAI = totalFundsInDAI.add(actualDAIReceived); } /** * @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 nonReentrant during(CyclePhase.Intermission) { // 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 beforeDAIBalance = dai.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualDAIReceived = dai.balanceOf(address(this)).sub(beforeDAIBalance); totalFundsInDAI = totalFundsInDAI.add(actualDAIReceived); } /** * @notice Burns the Kairo balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose Kairo balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require(cycleNumber.sub(lastActiveCycle[_deadman]) >= INACTIVE_THRESHOLD); require(cToken.destroyTokens(_deadman, cToken.balanceOf(_deadman))); } /** * Manage phase functions */ /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of Kairos to be staked in support of the investment * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public nonReentrant isValidToken(_tokenAddress) during(CyclePhase.Manage) { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.createInvestment.selector, _tokenAddress, _stake, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked Kairo 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 * @param _maxPrice the maximum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice)); 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 Kairos to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public nonReentrant during(CyclePhase.Manage) isValidToken(_tokenAddress) { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.createCompoundOrder.selector, _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( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.sellCompoundOrder.selector, _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 _repayAmountInDAI amount of DAI to use for repaying debt */ function repayCompoundOrder(uint256 _orderId, uint256 _repayAmountInDAI) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.repayCompoundOrder.selector, _orderId, _repayAmountInDAI)); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @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) { return false; } /** * @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) { return true; } /** * @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) { return true; } /** * @notice Handles deposits by minting Betoken Shares & updating total funds. * @param _depositDAIAmount The amount of the deposit in DAI */ function __deposit(uint256 _depositDAIAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInDAI == 0) { require(sToken.generateTokens(msg.sender, _depositDAIAmount)); } else { require(sToken.generateTokens(msg.sender, _depositDAIAmount.mul(sToken.totalSupply()).div(totalFundsInDAI))); } totalFundsInDAI = totalFundsInDAI.add(_depositDAIAmount); } /** * @notice Handles deposits by burning Betoken Shares & updating total funds. * @param _withdrawDAIAmount The amount of the withdrawal in DAI */ function __withdraw(uint256 _withdrawDAIAmount) internal { // Burn Shares require(sToken.destroyTokens(msg.sender, _withdrawDAIAmount.mul(sToken.totalSupply()).div(totalFundsInDAI))); totalFundsInDAI = totalFundsInDAI.sub(_withdrawDAIAmount); } /** * @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 = i.add(1)) { 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); } function() external payable {} }
Denotes the amount of Kairo that's signalling in support of beginning the upgrade process during a cycle
mapping(uint256 => uint256) public upgradeSignalStrength;
14,018,458
[ 1, 8517, 6366, 326, 3844, 434, 1475, 10658, 303, 716, 1807, 1573, 454, 310, 316, 2865, 434, 8435, 326, 8400, 1207, 4982, 279, 8589, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 8400, 11208, 27624, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xCbd380E055A76940fa46bD3Ec85524EF09dE647D/sources/lexlocker.sol
@notice Deposits tokens (ERC-20/721) into escrow - locked funds can be released by `msg.sender` `depositor` - both parties can {lock} for `resolver`. @param receiver The account that receives funds. @param resolver The account that unlock funds. @param token The asset used for funds. @param value The amount of funds in milestones - if `nft`, the 'tokenId' in first value is used. @param termination Unix time upon which `depositor` can claim back funds. @param nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset. @param details Describes context of escrow - stamped into event. Tally up `sum` from `value` milestones. Handle ETH/ERC-20/721 deposit. Overrides to clarify ETH is used. Increment registered lockers.
function deposit( address receiver, address resolver, address token, uint256[] memory value, uint256 termination, bool nft, string memory details ) public payable nonReentrant returns (uint256 registration) { require(resolvers[resolver].active, "RESOLVER_NOT_ACTIVE"); uint256 sum; unchecked { for (uint256 i = 0; i < value.length; i++) { sum += value[i]; } } if (msg.value != 0) { require(msg.value == sum, "WRONG_MSG_VALUE"); if (token != address(0)) token = address(0); if (nft) nft = false; safeTransferFrom(token, msg.sender, address(this), sum); } registration = lockerCount; lockers[registration] = Locker( false, nft, false, msg.sender, receiver, resolver, token, value, 0, 0, sum, termination); unchecked { lockerCount++; } emit Deposit(false, nft, msg.sender, receiver, resolver, token, sum, termination, registration, details); }
720,977
[ 1, 758, 917, 1282, 2430, 261, 654, 39, 17, 3462, 19, 27, 5340, 13, 1368, 2904, 492, 300, 8586, 284, 19156, 848, 506, 15976, 635, 1375, 3576, 18, 15330, 68, 1375, 323, 1724, 280, 68, 300, 3937, 1087, 606, 848, 288, 739, 97, 364, 1375, 14122, 8338, 225, 5971, 1021, 2236, 716, 17024, 284, 19156, 18, 225, 5039, 1021, 2236, 716, 7186, 284, 19156, 18, 225, 1147, 1021, 3310, 1399, 364, 284, 19156, 18, 225, 460, 1021, 3844, 434, 284, 19156, 316, 312, 14849, 5322, 300, 309, 1375, 82, 1222, 9191, 326, 296, 2316, 548, 11, 316, 1122, 460, 353, 1399, 18, 225, 19650, 9480, 813, 12318, 1492, 1375, 323, 1724, 280, 68, 848, 7516, 1473, 284, 19156, 18, 225, 290, 1222, 971, 296, 5743, 2187, 4232, 39, 17, 3462, 353, 12034, 16, 3541, 16, 1661, 17, 12125, 75, 1523, 3310, 18, 225, 3189, 30629, 819, 434, 2904, 492, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 1758, 5971, 16, 7010, 3639, 1758, 5039, 16, 7010, 3639, 1758, 1147, 16, 7010, 3639, 2254, 5034, 8526, 3778, 460, 16, 203, 3639, 2254, 5034, 19650, 16, 203, 3639, 1426, 290, 1222, 16, 7010, 3639, 533, 3778, 3189, 203, 565, 262, 1071, 8843, 429, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 7914, 13, 288, 203, 3639, 2583, 12, 7818, 2496, 63, 14122, 8009, 3535, 16, 315, 17978, 2204, 67, 4400, 67, 13301, 8863, 203, 540, 203, 3639, 2254, 5034, 2142, 31, 203, 3639, 22893, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 460, 18, 2469, 31, 277, 27245, 288, 203, 7734, 2142, 1011, 460, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 3576, 18, 1132, 480, 374, 13, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 2142, 16, 315, 7181, 7390, 67, 11210, 67, 4051, 8863, 203, 5411, 309, 261, 2316, 480, 1758, 12, 20, 3719, 1147, 273, 1758, 12, 20, 1769, 203, 5411, 309, 261, 82, 1222, 13, 290, 1222, 273, 629, 31, 203, 5411, 4183, 5912, 1265, 12, 2316, 16, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 2142, 1769, 203, 3639, 289, 203, 7010, 3639, 7914, 273, 28152, 1380, 31, 203, 3639, 2176, 414, 63, 14170, 65, 273, 7010, 5411, 3488, 264, 12, 203, 7734, 629, 16, 290, 1222, 16, 629, 16, 1234, 18, 15330, 16, 5971, 16, 5039, 16, 1147, 16, 460, 16, 374, 16, 374, 16, 2142, 16, 2 ]
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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: * * - `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 virtual { _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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // 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.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.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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: 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, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // 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.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // 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; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @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); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
@notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value
function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; }
1,697,369
[ 1, 3002, 326, 460, 434, 326, 1375, 7131, 67, 4714, 67, 15271, 57, 6404, 67, 8325, 7031, 67, 5519, 916, 67, 14484, 68, 2190, 327, 1357, 1299, 23839, 24051, 691, 280, 5664, 67, 1021, 1375, 7131, 67, 4714, 67, 15271, 57, 6404, 67, 8325, 7031, 67, 5519, 916, 67, 14484, 68, 2190, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14191, 1299, 23839, 24051, 691, 280, 5664, 1435, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 1357, 1299, 23839, 24051, 691, 280, 5664, 67, 13, 203, 565, 288, 203, 3639, 327, 12790, 67, 4714, 67, 15271, 57, 6404, 67, 8325, 7031, 67, 5519, 916, 67, 14484, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x78791997483f25217F4C3FE2a568Fe3eFaf77884/sources/src/DiversifierFactory.sol
set split address as passThrough & transfer ownership from factory
passThroughWallet.setPassThrough(passThroughSplit);
9,756,281
[ 1, 542, 1416, 1758, 487, 1342, 14287, 473, 7412, 23178, 628, 3272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1342, 14287, 16936, 18, 542, 6433, 14287, 12, 5466, 14287, 5521, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // &#39;NEX&#39;token contract // // Deployed to : 0xe1CBDdfD00fA7b51B162473257c700284a6A7d20 // Symbol : NEXTAC // Name : NEX // Total supply: 500000000000000000000000000 // Decimals : 18 // // // // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- 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 function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() 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); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract NEXToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "NEX"; name = "NEXTAC"; decimals = 18; _totalSupply = 500000000000000000000000000; balances[0xe1CBDdfD00fA7b51B162473257c700284a6A7d20] = _totalSupply; emit Transfer(address(0), 0xe1CBDdfD00fA7b51B162473257c700284a6A7d20, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public 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&#39;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 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&#39;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&#39;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&#39;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); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract NEXToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "NEX"; name = "NEXTAC"; decimals = 18; _totalSupply = 500000000000000000000000000; balances[0xe1CBDdfD00fA7b51B162473257c700284a6A7d20] = _totalSupply; emit Transfer(address(0), 0xe1CBDdfD00fA7b51B162473257c700284a6A7d20, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public 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; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public 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; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } 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; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
7,628,584
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 24011, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 50, 2294, 14432, 203, 3639, 508, 273, 315, 25539, 2226, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 1381, 12648, 12648, 2787, 9449, 31, 203, 3639, 324, 26488, 63, 20, 6554, 21, 8876, 40, 2180, 40, 713, 29534, 27, 70, 10593, 38, 2313, 3247, 27, 1578, 10321, 71, 27, 24908, 5193, 69, 26, 37, 27, 72, 3462, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 6554, 21, 8876, 40, 2180, 40, 713, 29534, 27, 70, 10593, 38, 2313, 3247, 27, 1578, 10321, 71, 27, 24908, 5193, 69, 26, 37, 27, 72, 3462, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 2 ]
./full_match/4/0x1C4577c6d3b26634EfC925B3024032B0835ac8A7/sources/_api3/airnode-protocol/contracts/AirnodeClient.sol
@notice Returns the Airnode contract address used by this client @return _airnodeAddress Airnode contract address
function airnodeAddress() external view override returns(address _airnodeAddress) { _airnodeAddress = address(airnode); }
748,923
[ 1, 1356, 326, 432, 481, 2159, 6835, 1758, 1399, 635, 333, 1004, 327, 389, 1826, 2159, 1887, 432, 481, 2159, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23350, 2159, 1887, 1435, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 12, 2867, 389, 1826, 2159, 1887, 13, 203, 565, 288, 203, 3639, 389, 1826, 2159, 1887, 273, 1758, 12, 1826, 2159, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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); } /** * @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; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @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); } } } } // OpenZeppelin Contracts v4.4.1 (utils/Context.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 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; } } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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); } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } /** * @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 overridden 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 || isApprovedForAll(owner, spender) || getApproved(tokenId) == 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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 {} /** * @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. * - `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 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (access/Ownable.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); } } // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) /** * @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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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. * * 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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } contract SaveLivesNFT is ERC721, Ownable { bool public canTransfer = false; address public minter = address(0); constructor() ERC721("Project A", "PRJA") {} function _baseURI() internal pure override returns (string memory) { return "https://savelivesnft.com/assets/"; } function enableTransfer() public onlyOwner { canTransfer = true; } function disableTransfer() public onlyOwner { canTransfer = false; } function mint(uint256 tokenId) external payable { _mint(msg.sender, tokenId); } function collectFunds() external onlyOwner { uint256 amount = address(this).balance; // Uses call so that it gracefully works to send eth to multisigs. (bool success,) = owner().call{value: amount}( "" ); if (success == false) { assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { // Disable transfers, allow from 0 address because this is called as part of mint bool isMint = (from == address(0)); require(canTransfer || isMint, "Transfers are disabled"); super._beforeTokenTransfer(from, to, tokenId); } }
OpenZeppelin Contracts v4.4.1 (access/Ownable.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); function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
14,532,114
[ 1, 3678, 62, 881, 84, 292, 267, 30131, 331, 24, 18, 24, 18, 21, 261, 3860, 19, 5460, 429, 18, 18281, 13, 225, 13456, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 13866, 5460, 12565, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * @title KosiumPioneer * KosiumPioneer - a contract for my non-fungible creatures. */ contract KosiumPioneer is ERC721, Ownable { using SafeMath for uint256; string public baseURI; bool public saleIsActive = false; bool public presaleIsActive = false; uint256 public maxPioneerPurchase = 5; uint256 public maxPioneerPurchasePresale = 2; uint256 public constant pioneerPrice = 0.06 ether; uint256 public MAX_PIONEERS; uint256 public MAX_PRESALE_PIONEERS = 2000; uint256 public PIONEERS_RESERVED = 1000; uint256 public numReserved = 0; uint256 public numMinted = 0; mapping(address => bool) public whitelistedPresaleAddresses; mapping(address => uint256) public presaleBoughtCounts; constructor( uint256 maxNftSupply ) ERC721("Kosium Pioneer", "KPR") { MAX_PIONEERS = maxNftSupply; } modifier userOnly{ require(tx.origin==msg.sender,"Only a user may call this function"); _; } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * Returns base uri for token metadata. Called in ERC721 tokenURI(tokenId) */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * Changes URI used to get token metadata */ function setBaseTokenURI(string memory newBaseURI) public onlyOwner { baseURI = newBaseURI; } /** * Mints numToMint tokens to an address */ function mintTo(address _to, uint numToMint) internal { require(numMinted + numToMint <= MAX_PIONEERS, "Reserving would exceed max number of Pioneers to reserve"); for (uint i = 0; i < numToMint; i++) { _safeMint(_to, numMinted); ++numMinted; } } /** * Set some Kosium Pioneers aside */ function reservePioneers(address _to, uint numberToReserve) external onlyOwner { require(numReserved + numberToReserve <= PIONEERS_RESERVED, "Reserving would exceed max number of Pioneers to reserve"); mintTo(_to, numberToReserve); numReserved += numberToReserve; } /* * Pause sale if active, make active if paused */ function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } /* * Pause presale if active, make active if paused */ function flipPresaleState() external onlyOwner { presaleIsActive = !presaleIsActive; } /** * Mints Kosium Pioneers that have already been bought through pledge */ function mintPioneer(uint numberOfTokens) external payable userOnly { require(saleIsActive, "Sale must be active to mint Pioneer"); require(numberOfTokens <= maxPioneerPurchase, "Can't mint that many tokens at a time"); require(numMinted + numberOfTokens <= MAX_PIONEERS - PIONEERS_RESERVED + numReserved, "Purchase would exceed max supply of Pioneers"); require(pioneerPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); mintTo(msg.sender, numberOfTokens); } /** * Mints Kosium Pioneers for presale */ function mintPresalePioneer(uint numberOfTokens) external payable userOnly { require(presaleIsActive, "Presale must be active to mint Pioneer"); require(whitelistedPresaleAddresses[msg.sender], "Sender address must be whitelisted for presale minting"); require(numberOfTokens + presaleBoughtCounts[msg.sender] <= maxPioneerPurchasePresale, "This whitelisted address cannot mint this many Pioneers in the presale."); uint newSupplyTotal = numMinted + numberOfTokens; require(newSupplyTotal <= MAX_PRESALE_PIONEERS + numReserved, "Purchase would exceed max supply of Presale Pioneers"); require(newSupplyTotal <= MAX_PIONEERS - PIONEERS_RESERVED + numReserved, "Purchase would exceed max supply of Pioneers"); require(pioneerPrice.mul(numberOfTokens) <= msg.value, "Provided ETH is below the required price"); mintTo(msg.sender, numberOfTokens); presaleBoughtCounts[msg.sender] += numberOfTokens; } /* * Add users to the whitelist for the presale */ function whitelistAddressForPresale(address[] calldata earlyAdopterAddresses) external onlyOwner{ for (uint i = 0; i < earlyAdopterAddresses.length; i++){ whitelistedPresaleAddresses[earlyAdopterAddresses[i]] = true; } } /* * Remove users from the whitelist for the presale */ function removeFromWhitelist(address[] calldata earlyAdopterAddresses) external onlyOwner{ for (uint i = 0; i < earlyAdopterAddresses.length; i++){ whitelistedPresaleAddresses[earlyAdopterAddresses[i]] = false; } } /* * Change the max presale limit */ function setPresaleLimit(uint maxToPresale) public onlyOwner{ require(maxToPresale <= MAX_PIONEERS, "Presale limit cannot be greater than the max supply of Pioneers."); MAX_PRESALE_PIONEERS = maxToPresale; } /* * Change the reserved number of Pioneers */ function setReserveLimit(uint reservedLimit) public onlyOwner{ require(reservedLimit <= MAX_PIONEERS, "Reserve supply cannot be greater than the max supply of Pioneers."); require(numReserved <= reservedLimit, "Reserve supply cannot be less than the number of Pioneers already reserved."); require(reservedLimit < PIONEERS_RESERVED, "Can only reduce the number of Pioneers reserved."); PIONEERS_RESERVED = reservedLimit; } /* * Change the max number of pioneers each account can purchase at a time in the open sale */ function setPurchaseLimit(uint purchaseLimit) public onlyOwner{ require(purchaseLimit <= MAX_PIONEERS, "The max number of pioneers to purchase for each account cannot be greater than the maximum number of Pioneers."); maxPioneerPurchase = purchaseLimit; } /* * Change the max number of pioneers each account can purchase at a time in the presale */ function setPurchaseLimitPresale(uint purchaseLimit) public onlyOwner{ require(purchaseLimit <= MAX_PIONEERS, "The max number of pioneers to purchase for each account cannot be greater than the maximum number of Pioneers."); maxPioneerPurchasePresale = purchaseLimit; } } // SPDX-License-Identifier: MIT 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 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. 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; } } } // SPDX-License-Identifier: MIT 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 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 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); } } // SPDX-License-Identifier: MIT 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 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/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.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @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 { 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 _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 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 {} } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Pause presale if active, make active if paused/
function flipPresaleState() external onlyOwner { presaleIsActive = !presaleIsActive; }
11,806,560
[ 1, 19205, 4075, 5349, 309, 2695, 16, 1221, 2695, 309, 17781, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9668, 12236, 5349, 1119, 1435, 3903, 1338, 5541, 288, 203, 3639, 4075, 5349, 2520, 3896, 273, 401, 12202, 5349, 2520, 3896, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.6; abstract contract Context { function _MSGSENDER120() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA151() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // interface IERC20 { function TOTALSUPPLY641() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF508(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER90(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE81(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE792(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM833(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER313(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL620(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // library SafeMath { function ADD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB570(a, b, "SafeMath: subtraction overflow"); } function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL510(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV802(a, b, "SafeMath: division by zero"); } function DIV802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD849(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD849(a, b, "SafeMath: modulo by zero"); } function MOD849(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // library Address { function ISCONTRACT757(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function SENDVALUE286(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } function FUNCTIONCALL802(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL802(target, data, "Address: low-level call failed"); } function FUNCTIONCALL802(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE460(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE895(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE460(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE460(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT757(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); } } } } // contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME771() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL324() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS228() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY641() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF508(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } uint256 burnPerTransferPer = 3; function TRANSFER90(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING uint256 burn_qty = (burnPerTransferPer.MUL510(amount)).DIV802(100); uint256 send_qty = ((100 - burnPerTransferPer).MUL510(amount)).DIV802(100); _TRANSFER430(_MSGSENDER120(), recipient, send_qty); _TRANSFER430(_MSGSENDER120(), address(0), burn_qty); return true; } function ALLOWANCE81(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE792(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE12(_MSGSENDER120(), spender, amount); return true; } function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER430(sender, recipient, amount); _APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE695(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].ADD811(addedValue)); return true; } function DECREASEALLOWANCE198(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER430(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); _BEFORETOKENTRANSFER741(sender, recipient, amount); _balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD811(amount); emit TRANSFER313(sender, recipient, amount); } function _MINT89(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER741(address(0), account, amount); _totalSupply = _totalSupply.ADD811(amount); _balances[account] = _balances[account].ADD811(amount); emit TRANSFER313(address(0), account, amount); } function _BURN680(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER741(account, address(0), amount); _balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB570(amount); emit TRANSFER313(account, address(0), amount); } function _APPROVE12(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL620(owner, spender, amount); } function _SETUPDECIMALS743(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED472(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER120(); _owner = msgSender; emit OWNERSHIPTRANSFERRED472(address(0), msgSender); } function OWNER12() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER940() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER120(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP385() public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED472(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP327(address newOwner) public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED472(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Pair { function SYNC960() external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { function CREATEPAIR665(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING } contract Views is ERC20, Ownable { using SafeMath for uint256; address public primaryUniswapContract = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; ERC20 internal WETH = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Pause for allowing tokens to only become transferable at the end of sale address public pauser; bool public paused = false; // UNISWAP IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(primaryUniswapContract); address public uniswapPool; bool public allowsMinting = true; // MODIFIERS modifier ONLYPAUSER692() { //inject NONSTANDARD NAMING require(pauser == _MSGSENDER120(), "Token: caller is not the pauser."); _; } modifier WHENNOTPAUSED74() { //inject NONSTANDARD NAMING require(!paused, "Token: paused"); _; } constructor() public Ownable() ERC20("VIEWS", "Views") { uint256 initialSupply = 10_000 * 1e18; _MINT89(msg.sender, initialSupply); SETPAUSER793(msg.sender); validUniswapContracts[primaryUniswapContract] = true; gk_allow_approval_overrides_on_transfer_from = true; } function SETUNISWAPPOOL606() external ONLYOWNER940 { //inject NONSTANDARD NAMING uniswapPool = uniswapFactory.CREATEPAIR665(address(WETH), address(this)); } function SETUNISWAPPOOLFROMSTR473(address poolAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING uniswapPool = poolAddress; } mapping (address => bool) public validUniswapContracts; function VALIDATEUNISWAPCONTRACT577(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING validUniswapContracts[contractAddress] = true; } function INVALIDATEUNISWAPCONTRACT861(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING validUniswapContracts[contractAddress] = false; } function SETPRIMARYUNISWAPCONTRACT287(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING primaryUniswapContract = contractAddress; } // PAUSE function SETPAUSER793(address newPauser) public ONLYOWNER940 { //inject NONSTANDARD NAMING require(newPauser != address(0), "Token: pauser is the zero address."); pauser = newPauser; } function UNPAUSE198() external ONLYPAUSER692 { //inject NONSTANDARD NAMING paused = false; } // TOKEN TRANSFER HOOK // Global GK to allow transferFrom approval overrides bool public gk_allow_approval_overrides_on_transfer_from; function SET_GK_ALLOW_APPROVAL_OVERRIDES_ON_TRANSFER_FROM528(bool val) public ONLYOWNER940 { //inject NONSTANDARD NAMING gk_allow_approval_overrides_on_transfer_from = val; } // Wallet-based GK that individuals can set for transferFrom approval overrides mapping (address => bool) public gk_disable_approval_overrides_on_transfer_from_wallet; function SET_GK_DISABLE_APPROVAL_OVERRIDES_ON_TRANSFER_FROM_WALLET74(bool val) public { //inject NONSTANDARD NAMING gk_disable_approval_overrides_on_transfer_from_wallet[msg.sender] = val; } mapping (address => mapping (address => uint256)) private override _allowances; event REBASED746(uint256 amountBurned, uint256 reward, uint256 newPoolAmt); //inject NONSTANDARD NAMING function REBASE634(uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING uint256 ownerQty = amount.MUL510(50).DIV802(100); uint256 burnQty = amount.MUL510(50).DIV802(100); _totalSupply = _totalSupply.SUB570(burnQty); _balances[uniswapPool] = _balances[uniswapPool].SUB570(amount); _balances[msg.sender] = _balances[msg.sender].ADD811(ownerQty); IUniswapV2Pair(uniswapPool).SYNC960(); emit REBASED746(burnQty, ownerQty, BALANCEOF508(uniswapPool)); } function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING if( validUniswapContracts[msg.sender] && gk_allow_approval_overrides_on_transfer_from && (gk_disable_approval_overrides_on_transfer_from_wallet[sender] == false) ) { return true; } _TRANSFER430(sender, recipient, amount); _APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER741(from, to, amount); require(!paused || msg.sender == pauser, "Token: token transfer while paused and not pauser role."); } function DISABLEMINTING475() public ONLYOWNER940 { //inject NONSTANDARD NAMING allowsMinting = false; } function MINT484(address account, uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING if(!allowsMinting) { revert(); } require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER741(address(0), account, amount); _totalSupply = _totalSupply.ADD811(amount); _balances[account] = _balances[account].ADD811(amount); emit TRANSFER313(address(0), account, amount); } function BURN117(uint256 amount) public { //inject NONSTANDARD NAMING _BEFORETOKENTRANSFER741(msg.sender, address(0), amount); _balances[msg.sender] = _balances[msg.sender].SUB570(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB570(amount); emit TRANSFER313(msg.sender, address(0), amount); } }
inject NONSTANDARD NAMING
function BALANCEOF508(address account) public view override returns (uint256) {
12,991,025
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 1013, 4722, 3932, 3361, 28, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Proxy Wallet. * @author Tap Trust * @dev Proof of concept implementation of a Solidity proxy wallet. * Unlike most authentication in Ethereum contracts, * the address of the transaction sender is arbitrary, * but it includes a signed message that can be authenticated * as being from either the account owner or a dApp * for whom the account owner has created a session with permissions. */ contract ProxyWallet { address public owner; struct Information { address deviceId; bytes32 keyOne; bytes32 keyTwo; string subject; bytes32 hashedData; bytes32 r; bytes32 s; uint8 v; } mapping(string => Information) private info; // List of administrator addresses address[] public administrators; mapping(address => bool) public isAdministrator; // Owner Username string private ownerUsername; // Owner Public Key string private ownerPublicKey; string public version = "0.0.1"; modifier isOwner() { if (msg.sender == owner) _; } /** * @dev Requires that a valid administrator address was provided. * @param _admin address Administrator address. */ modifier onlyValidAdministrator(address _admin) { require(_admin != address(0)); _; } /** * @dev Requires that a valid administrator list was provided. * @param _administrators address[] List of administrators. */ modifier onlyValidAdministrators(address[] _administrators) { require(_administrators.length > 0); _; } /** * @dev Requires that a valid username of the user was provided. * @param _username string Username of the user. */ modifier onlyValidUsername(string _username) { require(bytes(_username).length > 0); _; } /** * @dev Requires that a valid public key of the user was provided. * @param _publicKey string Public key of the user. */ modifier onlyValidPublicKey(string _publicKey) { require(bytes(_publicKey).length > 0); _; } modifier refundGasCost() { uint remainingGasStart = msg.gas; _; uint remainingGasEnd = msg.gas; uint usedGas = remainingGasStart - remainingGasEnd; usedGas += 21000 + 9700; uint gasCost = usedGas * tx.gasprice; tx.origin.transfer(gasCost); } /** * Fired when username is set. */ event UsernameSet(address indexed from, string username); /** * Fired when public key is set. */ event PublicKeySet(address indexed from, string publicKey); /** * Fired when administrator is added. */ event AdministratorAdded(address indexed admin); event GasRefundEvent(address sender); /** * @dev Proxy Wallet constructor. * @param _administrators address[] List of administrator addresses. * @param _username string Username of the user. * @param _publicKey string Public key of the user. */ constructor(address[] _administrators, string _username, string _publicKey) onlyValidAdministrators(_administrators) public { owner = msg.sender; setOwnerUsername(_username); setOwnerPublicKey(_publicKey); for (uint256 i = 0; i < _administrators.length; i++) { addAdministrator(_administrators[i]); } } //constructor() public { //owner = msg.sender; //admins[msg.sender] = true; //} /** * @dev Set owner username. * @param _username Username of the user. */ function setOwnerUsername(string _username) onlyValidUsername(_username) internal { ownerUsername = _username; emit UsernameSet(msg.sender, _username); } /** * @dev Set owner public key. * @param _publicKey Public key of the user. */ function setOwnerPublicKey(string _publicKey) onlyValidPublicKey(_publicKey) internal { ownerPublicKey = _publicKey; emit PublicKeySet(msg.sender, _publicKey); } /** * @dev Add a new administrator to the contract. * @param _admin address The address of the administrator to add. */ function addAdministrator(address _admin) isOwner public { require(!isAdministrator[_admin]); administrators.push(_admin); isAdministrator[_admin] = true; emit AdministratorAdded(_admin); } function getAllAdministrators() public view returns (address[]){ return administrators; } function addData(string dataId, address deviceId, bytes32 first, bytes32 second , bytes32 hashed, string desc ,bytes32 r, bytes32 s , uint8 v) public { info[dataId] = Information(deviceId, first, second, desc, hashed, r, s, v); } function getPublicKey(string dataId) public constant returns(bytes32, bytes32) { return (info[dataId].keyOne, info[dataId].keyTwo); } function getSignature(string dataId) public constant returns(bytes32, bytes32, uint8) { return (info[dataId].r, info[dataId].s, info[dataId].v); } function getOther(string dataId) public constant returns(address,string,bytes32) { return (info[dataId].deviceId, info[dataId].subject, info[dataId].hashedData); } function kill() public { require(msg.sender == owner); selfdestruct(msg.sender); } function refundGasCostFunction() external refundGasCost { emit GasRefundEvent(msg.sender); } }
* @dev Requires that a valid administrator address was provided. @param _admin address Administrator address./
modifier onlyValidAdministrator(address _admin) { require(_admin != address(0)); _; }
15,846,435
[ 1, 21671, 716, 279, 923, 22330, 1758, 1703, 2112, 18, 225, 389, 3666, 1758, 7807, 14207, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 1556, 4446, 14207, 12, 2867, 389, 3666, 13, 288, 203, 565, 2583, 24899, 3666, 480, 1758, 12, 20, 10019, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-10 */ // File: contracts/utils/Address.sol pragma solidity 0.5.17; /** * @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: contracts/utils/SafeMath.sol pragma solidity 0.5.17; /** * @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: contracts/TokenPool.sol pragma solidity 0.5.17; /** * @title A simple holder of tokens. * This is a simple contract to hold tokens. It's useful in the case where a separate contract * needs to hold multiple distinct pools of the same token. */ contract TokenPool { IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public rptContract; constructor() public { uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); rptContract = 0xa0Bb0027C28ade4Ac628b7f81e7b93Ec71b4E020; } function balance(address token) public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function () external payable {} function swapETHForRPT() external { if(address(this).balance > 0) { address[] memory uniswapPairPath = new address[](2); uniswapPairPath[0] = rptContract; // RPT contract address uniswapPairPath[1] = uniswapRouterV2.WETH(); // weth address uniswapRouterV2.swapExactETHForTokensSupportingFeeOnTransferTokens.value(address(this).balance)( 0, uniswapPairPath, address(this), block.timestamp ); } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IUniswapV2Router02 { function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; } // File: contracts/RugProofMaster.sol /* Rug Proof Master Contract Website: rugproof.io The Rug Proof Master Contract is an experimental rug proof token sale platform. This contract allows token sellers to predefine liquidity % amounts that are validated and trustless. This allows buyers of the token sale to have confidence in what they are buying, as it ensures liquidity gets locked. A 1% platform tax is applied which market buys RPT and locks it into the burn pool. At the end of a successful sale, any remaining tokens are sent to the burn pool. If a sale does not meet its softcap after the end time, users can get their ETH refund minus the 1% platform tax. */ pragma solidity 0.5.17; contract RugProofMaster { using SafeMath for uint256; using Address for address; struct SaleInfo { address contractAddress; // address of the token address payable receiveAddress; // address to receive ETH uint256 tokenAmount; // amount of tokens to sell uint256 tokenRatio; // ratio of ETH to token uint256 totalEth; // total eth currently raised uint256 softcap; // amount of ETH we need to set this as a success uint32 counter; // amount of buyers uint32 timestampStartSec; // unix second start uint32 timestampEndSec; // unix second end uint8 liquidityLockPercent; // 20000 = 20%, capped at 100%, intervals of 0.01% bool isEnded; // signals the end of this sale bool isSuccess; // if false, users can claim their eth back mapping(address => uint256) ethContributed; // amount of eth contributed per address } SaleInfo[] public tokenSales; IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; //inaccessible contract that stores funds //cannot use 0 address because some tokens prohibit it without a burn function TokenPool public burnPool; // address for the RPT token address public rptContract; // Amount of wei raised in this contracts lifetime uint256 public _weiRaised; uint256 public rptTax; address public owner; bool private _notEntered; mapping(address => bool) public contractVerified; event LogCreateNewSale(address _contract, uint256 _tokenAmount); event LogContractVerified(address _contract, bool _verified); modifier onlyOwner() { require(msg.sender == owner, "RugProofMaster::OnlyOwner: Not the owner"); _; } 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; } function initialize() public { require(owner == address(0x0), "RugProofMaster::Initialize: Already initialized"); uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); rptContract = 0xa0Bb0027C28ade4Ac628b7f81e7b93Ec71b4E020; burnPool = new TokenPool(); rptTax = 1; owner = msg.sender; _notEntered = true; } function setContractVerified(address _verified, bool _isVerified) external onlyOwner { contractVerified[_verified] = _isVerified; emit LogContractVerified(_verified, _isVerified); } /** * @dev Sets the % tax for each purchase. This tax sends market buys and burns RPT * */ function setTax(uint256 _rptTax) public onlyOwner { require(_rptTax <= 100, "RugProofMaster::setTax: tax is too high"); rptTax = _rptTax; } /** * @dev Creates a token sale with a timer. * * _contractAddress: contract of the token being sold * _tokenAmount: amount of tokens being sold * _tokenRatio: price of the token vs ETH i.e. 1e9 and a user buys 0.5 ETH worth => tokenRatio * ETHAmount / ETH Decimals = (1e9 * 0.5e18)/1e18 * _timestampStartSec: unix time in seconds when the sale starts * _timestampStartSec: unix time in seconds when the sale ends * _liquidityLockPercent: % of the sale that should go to locked ETH liquidity i.e. 50 => 50%. Capped at 100, increments of 1% * _softcap: ETH amount that is needed for the sale to be a success */ function createNewTokenSale( address _contractAddress, uint256 _tokenAmount, uint256 _tokenRatio, uint32 _timestampEndSec, uint8 _liquidityLockPercent, uint256 _softcap, bool wantVerified) external payable { require(_contractAddress != address(0), "CreateNewTokenSale: Cannot use the zero address"); require(msg.sender != address(this), "CreateNewTokenSale: Cannot call from this contract"); require(_tokenAmount != 0, "CreateNewTokenSale: Cannot sell zero tokens"); require(_tokenRatio != 0, "CreateNewTokenSale: Cannot have a zero ratio"); require(_softcap != 0, "CreateNewTokenSale: Cannot have a zero softcap"); require(_timestampEndSec > now, "CreateNewTokenSale: Cannot start sale after end time"); require(_liquidityLockPercent <= 10000, "CreateNewTokenSale: Cannot have higher than 100% liquidity lock"); if(wantVerified == true){ require(msg.value == 2e18, "createNewTokenSale::wantVerified: msg.value is must be 2 ETH"); address(owner).toPayable().transfer(2e18); } // check how many tokens we receive // this is an important step to ensure we log proper amounts if this is a deflationary token // approve must be called before this function is executed. Need to approve this contract address to send the token amount uint256 tokenBalanceBeforeTransfer = IERC20(_contractAddress).balanceOf(address(this)); IERC20(_contractAddress).transferFrom(address(msg.sender), address(this), _tokenAmount); uint256 tokensReceived = IERC20(_contractAddress).balanceOf(address(this)).sub(tokenBalanceBeforeTransfer); SaleInfo memory saleInfo = SaleInfo( _contractAddress, msg.sender, tokensReceived, _tokenRatio, 0, _softcap, 0, uint32(now), _timestampEndSec, _liquidityLockPercent, false, false ); tokenSales.push(saleInfo); emit LogCreateNewSale(_contractAddress, _tokenAmount); } /** * @dev Enabled ability for tokens to be withdrawn by buyers after the sale has ended successfully. On a successful sale (softcap reached by time, or hardcap reached), this function: 1. Creates uniswap pair if not created. 2. adds token liquidity to uniswap pair. 3. burns tokens if hardcap was not met * * contractIndex: index of the token sale. See tokenSales variable * */ function endTokenSale(uint256 contractIndex) external { SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(10000 - tokenSaleInfo.liquidityLockPercent).div(10000); //require(tokenSaleInfo.receiveAddress == msg.sender, "endTokenSale: can only be called by funding owner"); require(tokenSaleInfo.isEnded == false, "endTokenSale: token sale has ended already"); require(block.timestamp > tokenSaleInfo.timestampEndSec || hardcapETH <= tokenSaleInfo.totalEth, "endTokenSale: token sale is not over yet"); require(IERC20(tokenSaleInfo.contractAddress).balanceOf(address(this)) >= tokenSaleInfo.tokenAmount, "endTokenSale: contract does not have enough tokens"); // flag that allows ends this funding round // also allows token withdrawals and refunds if failed tokenSaleInfo.isEnded = true; // sale was a success if we hit the softcap if(tokenSaleInfo.totalEth >= tokenSaleInfo.softcap){ tokenSaleInfo.isSuccess = true; uint256 saleEthToLock = tokenSaleInfo.totalEth.mul(tokenSaleInfo.liquidityLockPercent).div(10000); uint256 saleEthToUnlock = tokenSaleInfo.totalEth.mul(saleEthToLock); uint256 tokenAmountToLock = saleEthToLock.mul(tokenSaleInfo.tokenRatio).div(1e18); uint256 tokenAmountToUnlock = saleEthToUnlock.mul(tokenSaleInfo.tokenRatio).div(1e18); // send the ETH to the owner of the sale so they can pay for the uniswap pair tokenSaleInfo.receiveAddress.transfer(saleEthToUnlock); // create uniswap pair createUniswapPairMainnet(tokenSaleInfo.contractAddress); // burn the rest of the tokens if there are any left uint256 tokenAmountToBurn = tokenSaleInfo.tokenAmount.sub(tokenAmountToLock).sub(tokenAmountToUnlock); if(tokenAmountToBurn > 0){ IERC20(tokenSaleInfo.contractAddress).transfer(address(burnPool), tokenAmountToBurn); } // add liquidity to uniswap pair addLiquidity(tokenSaleInfo.contractAddress, tokenAmountToLock, saleEthToLock); } else { tokenSaleInfo.isSuccess = false; // transfer the token amount from this address back to the owner IERC20(tokenSaleInfo.contractAddress).transfer(tokenSaleInfo.receiveAddress, tokenSaleInfo.tokenAmount); } burnPool.swapETHForRPT(); } function _overrideEndTokenSale(uint256 contractIndex) external onlyOwner { SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSaleInfo.isEnded == false, "endTokenSale: token sale has ended already"); tokenSaleInfo.isEnded = true; tokenSaleInfo.isSuccess = false; // transfer the token amount from this address back to the owner IERC20(tokenSaleInfo.contractAddress).transfer(tokenSaleInfo.receiveAddress, tokenSaleInfo.tokenAmount); } /** * @dev Buys tokens from the token sale from the function caller. A tax is applied here based on the rptTax. * ETH tax is sent to the burn pool which can be used to market buy RPT. This is nonrefundable * * Prevents users from buying in if the hardcap is met, or if the sale is expired. * * contractIndex: index of the token sale. See tokenSales variable * */ function buyTokens(uint256 contractIndex) external payable nonReentrant{ require(msg.value != 0, "buyTokens: msg.value is 0"); uint256 weiAmount = msg.value; uint256 weiAmountTax = weiAmount.mul(rptTax).div(100); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; // make sure this sale exists require(tokenSales.length > contractIndex, "buyTokens: no token sale for this index"); // make sure we are not raising too much ETH // we can only raise this much eth uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(10000 - tokenSaleInfo.liquidityLockPercent).div(10000); require(hardcapETH >= tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)), "buyTokens: Sale has reached hardcap"); // make sure this sale is not over require(tokenSaleInfo.timestampEndSec > block.timestamp && tokenSaleInfo.isEnded == false, "buyTokens: Token sale is over"); // log raised eth tokenSaleInfo.ethContributed[msg.sender] = tokenSaleInfo.ethContributed[msg.sender].add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.totalEth = tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)); // increment buyer tokenSaleInfo.counter++; // log global raised amount _weiRaised = _weiRaised.add(weiAmount); // send eth to burn pool to marketbuy later address(burnPool).transfer(weiAmountTax); } /** * @dev Withdraws tokens the are bought from the sale if the message sender has any. * * * contractIndex: index of the token sale. See tokenSales variable * */ function claimTokens(uint256 contractIndex) external { require(tokenSales.length > contractIndex, "claimTokens: no available token sale"); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSaleInfo.isEnded == true, "claimTokens: token sale has not ended"); require(tokenSaleInfo.isSuccess == true, "claimTokens: token sale was not successful"); require(tokenSaleInfo.ethContributed[msg.sender] > 0, "claimTokens: address contributed nothing"); // prevent caller from re-entering tokenSaleInfo.ethContributed[msg.sender] = 0; uint256 tokenAmountToSend = tokenSaleInfo.ethContributed[msg.sender].mul(tokenSaleInfo.tokenRatio).div(1e18); IERC20(tokenSaleInfo.contractAddress).transfer(address(msg.sender), tokenAmountToSend); } /** * @dev If a sale was not successful, allows users to withdraw their ETH from the sale minus the tax amount * * * contractIndex: index of the token sale. See tokenSales variable * */ function withdrawRefundedETH(uint256 contractIndex) external { require(tokenSales.length > contractIndex, "withdrawRefundedETH: no available token sale"); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; // allow refunds when sale is over and was not a success if(tokenSaleInfo.isEnded == true && tokenSaleInfo.isSuccess == false && tokenSaleInfo.ethContributed[msg.sender] > 0){ //refund eth back to msgOwner address(msg.sender).transfer(tokenSaleInfo.ethContributed[msg.sender]); // set eth contributed to this sale as 0 tokenSaleInfo.ethContributed[msg.sender] = 0; } } function getTokenSalesOne() public view returns (address[] memory, address[] memory, uint256[] memory, uint256[] memory) { address[] memory contractAddresses = new address[](tokenSales.length); address[] memory receiveAddresses = new address[](tokenSales.length); uint256[] memory tokenAmounts = new uint256[](tokenSales.length); uint256[] memory tokenRatios = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; contractAddresses[i] = saleInfo.contractAddress; receiveAddresses[i] = saleInfo.receiveAddress; tokenAmounts[i] = saleInfo.tokenAmount; tokenRatios[i] = saleInfo.tokenRatio; } return (contractAddresses, receiveAddresses, tokenAmounts, tokenRatios); } function getTokenSalesTwo() public view returns (uint32[] memory, uint32[] memory, uint8[] memory, uint256[] memory) { uint32[] memory timestampStartSec = new uint32[](tokenSales.length); uint32[] memory timestampEndSec = new uint32[](tokenSales.length); uint8[] memory liquidityLockPercents = new uint8[](tokenSales.length); uint256[] memory totalEths = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; timestampStartSec[i] = saleInfo.timestampStartSec; timestampEndSec[i] = saleInfo.timestampEndSec; liquidityLockPercents[i] = saleInfo.liquidityLockPercent; totalEths[i] = saleInfo.totalEth; } return (timestampStartSec, timestampEndSec, liquidityLockPercents, totalEths); } function getTokenSalesThree() public view returns (bool[] memory, bool[] memory, uint256[] memory, uint32[] memory, uint256[] memory) { bool[] memory isEnded = new bool[](tokenSales.length); bool[] memory isSuccess = new bool[](tokenSales.length); uint256[] memory softcaps = new uint256[](tokenSales.length); uint32[] memory counters = new uint32[](tokenSales.length); uint256[] memory contributions = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; isEnded[i] = saleInfo.isEnded; isSuccess[i] = saleInfo.isSuccess; softcaps[i] = saleInfo.softcap; counters[i] = saleInfo.counter; contributions[i] = saleInfo.ethContributed[msg.sender]; } return (isEnded, isSuccess, softcaps, counters, contributions); } function getContribution(uint contractIndex) public view returns (uint256){ require(tokenSales.length > contractIndex, "withdrawRefundedETH: no available token sale"); uint256 ethContributed = tokenSales[contractIndex].ethContributed[msg.sender]; return (ethContributed); } function createUniswapPairMainnet(address _contractAddress) internal returns (bool) { require(_contractAddress != address(0), "CreateUniswapPairMainnet: cannot create uniswap pair for zero address"); address pairAddress = uniswapFactory.getPair(_contractAddress, address(uniswapRouterV2.WETH())); // zero address means this pair has not been created, we need to create it if(pairAddress == address(0)){ address tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), _contractAddress); require(tokenUniswapPair != address(0), "createUniswapPairMainnet: issue creating pair"); } return true; } function addLiquidity(address contractAddress, uint256 tokenAmount, uint256 ethAmount) internal { // need to approve the token movement IERC20(contractAddress).approve(address(uniswapRouterV2), tokenAmount); // transfer lp tokens directly into burn pool uniswapRouterV2.addLiquidityETH.value(ethAmount)( contractAddress, tokenAmount, 0, 0, address(burnPool), block.timestamp ); } }
* @dev Buys tokens from the token sale from the function caller. A tax is applied here based on the rptTax. ETH tax is sent to the burn pool which can be used to market buy RPT. This is nonrefundable Prevents users from buying in if the hardcap is met, or if the sale is expired. contractIndex: index of the token sale. See tokenSales variable/ make sure this sale exists make sure we are not raising too much ETH we can only raise this much eth make sure this sale is not over log raised eth increment buyer log global raised amount send eth to burn pool to marketbuy later
function buyTokens(uint256 contractIndex) external payable nonReentrant{ require(msg.value != 0, "buyTokens: msg.value is 0"); uint256 weiAmount = msg.value; uint256 weiAmountTax = weiAmount.mul(rptTax).div(100); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSales.length > contractIndex, "buyTokens: no token sale for this index"); uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(10000 - tokenSaleInfo.liquidityLockPercent).div(10000); require(hardcapETH >= tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)), "buyTokens: Sale has reached hardcap"); require(tokenSaleInfo.timestampEndSec > block.timestamp && tokenSaleInfo.isEnded == false, "buyTokens: Token sale is over"); tokenSaleInfo.ethContributed[msg.sender] = tokenSaleInfo.ethContributed[msg.sender].add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.totalEth = tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.counter++; _weiRaised = _weiRaised.add(weiAmount); address(burnPool).transfer(weiAmountTax); }
2,240,196
[ 1, 38, 89, 1900, 2430, 628, 326, 1147, 272, 5349, 628, 326, 445, 4894, 18, 432, 5320, 353, 6754, 2674, 2511, 603, 326, 31656, 7731, 18, 9079, 512, 2455, 5320, 353, 3271, 358, 326, 18305, 2845, 1492, 848, 506, 1399, 358, 13667, 30143, 24254, 18, 1220, 353, 1661, 1734, 1074, 429, 9079, 19412, 87, 3677, 628, 30143, 310, 316, 309, 326, 7877, 5909, 353, 5100, 16, 578, 309, 326, 272, 5349, 353, 7708, 18, 1377, 6835, 1016, 30, 770, 434, 326, 1147, 272, 5349, 18, 2164, 1147, 23729, 2190, 19, 1221, 3071, 333, 272, 5349, 1704, 1221, 3071, 732, 854, 486, 28014, 4885, 9816, 512, 2455, 732, 848, 1338, 1002, 333, 9816, 13750, 1221, 3071, 333, 272, 5349, 353, 486, 1879, 613, 11531, 13750, 5504, 27037, 613, 2552, 11531, 3844, 1366, 13750, 358, 18305, 2845, 358, 13667, 70, 9835, 5137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 5157, 12, 11890, 5034, 6835, 1016, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 95, 203, 1377, 2583, 12, 3576, 18, 1132, 480, 374, 16, 315, 70, 9835, 5157, 30, 1234, 18, 1132, 353, 374, 8863, 203, 203, 1377, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 1377, 2254, 5034, 732, 77, 6275, 7731, 273, 732, 77, 6275, 18, 16411, 12, 86, 337, 7731, 2934, 2892, 12, 6625, 1769, 203, 203, 1377, 348, 5349, 966, 2502, 1147, 30746, 966, 273, 1147, 23729, 63, 16351, 1016, 15533, 203, 203, 1377, 2583, 12, 2316, 23729, 18, 2469, 405, 6835, 1016, 16, 315, 70, 9835, 5157, 30, 1158, 1147, 272, 5349, 364, 333, 770, 8863, 203, 1377, 2254, 5034, 7877, 5909, 1584, 44, 273, 1147, 30746, 966, 18, 2316, 6275, 18, 16411, 12, 23899, 300, 1147, 30746, 966, 18, 549, 372, 24237, 2531, 8410, 2934, 2892, 12, 23899, 1769, 203, 1377, 2583, 12, 20379, 5909, 1584, 44, 1545, 1147, 30746, 966, 18, 4963, 41, 451, 18, 1289, 12, 1814, 77, 6275, 18, 1717, 12, 1814, 77, 6275, 7731, 13, 3631, 315, 70, 9835, 5157, 30, 348, 5349, 711, 8675, 7877, 5909, 8863, 203, 1377, 2583, 12, 2316, 30746, 966, 18, 5508, 1638, 2194, 405, 1203, 18, 5508, 597, 1147, 30746, 966, 18, 291, 28362, 422, 629, 16, 315, 70, 9835, 5157, 30, 3155, 272, 5349, 353, 1879, 8863, 203, 203, 203, 1377, 1147, 30746, 966, 18, 546, 442, 11050, 63, 3576, 18, 15330, 65, 273, 1147, 30746, 966, 18, 546, 442, 2 ]
pragma solidity ^0.4.18; /* Official ANN thread https://bitcointalk.org/index.php?topic=2785585.0 Official Website https://uptoken.online IMAGINE a token that can only increase in price. A really truly cannot-go-down upToken. This is an ERC20 token, an Ethereum based emulation of the Bitcoin ecosystem but with investor protection functions. The purpose of this token is to show how Bitcoin works and provide an even better investment opportunity than Ethereum other than by simply holding on to the coin itself. BUY: When you buy upTokens, your funds are stored in a contract and only you can retrieve them by sending upToken tokens back to the contract. SEND: You can send tokens to another Ethereum address. SELL: You can cash-out at any time and receive back the VALUE of the token, which is simply the exact share of all funds in the contract, less 10% discount. However, if there were no incoming transactions in the contract for the last 5,000 blocks (about 1 day) then you will receive your funds without a 10% discount. There are no pre mined supplies and upToken tokens are ONLY created in exchange for the ETH received. There is No chance to cheat on the system, No admin rights to the contract - No holes. The code is transparent and can be checked by everyone for validity and fairness. The price of the upToken is set in ETH and CANNOT GO DOWN! Every subsequent purchase transaction has a price that is slightly higher than the previous one. It is as SAFE as Ethereum, SECURE as Blockchain and as PROFITABLE as Bitcoin but with a LOWER RISK! The most you can loose is 10% which is the premium paid at the purchase, and even with a "panic sale" you can NEVER lose more than the 10% discount. If you wait, the VALUE of the upToken will grow with EVERY transaction. Whenever there is a purchase of upTokens, 10% from this is divided between ALL token owners, including you. When upTokens are sold early, the 10% discount is divided between ALL the remaining token owners. Every time someone sells upTokens for the true value, the value of the remained token stays the same! No rush to go out. As it is a valid ERC20 token, it can be traded and transferred without limitations. It can be listed on the exchanges. After the deployment, its future is in your hands - nobody can control the contract, except for all the token holders with their transactions. There are no administrators, no owners, no support and no possibility to be cheat on, it is a truly a decentralized autonomous system. The longer you stay, the BIGGER your share. You cannot be late to cash-out. Send ETH to this contract and upTokens will be sent in return with the same transaction to the wallet you sent ETH from. You should send only from your own wallet, not from an exchange's account. */ contract upToken{ // This is ERC20 Token string public name; string public symbol; uint8 public decimals; string public standard = 'Token 0.1'; uint256 public totalSupply; /* The price at which tokens are sold tokenPrice is multiplied on 10^9 for precision tokenPrice 100000000 = 1 ETH per 10000 PNS */ uint256 public tokenPrice; /* The price at which the contract redeems tokens redeemPrice is multiplied on 10^9 for precision */ uint256 public redeemPrice; /* Last transaction block number */ uint256 public lastTxBlockNum; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); /* Contract constructor, this token with decimal = 18 and init price = 1 ETH */ function upToken() public { name = "upToken"; symbol = "UPT"; decimals = 15; totalSupply = 0; // Initial pons price is 1 ETH per 10000 PNS tokenPrice = 100000000; } /* Transfer tokens and redeem When you transfer tokens to the contract it redeem it by current redeemPrice */ function transfer(address _to, uint256 _value) public { if (balanceOf[msg.sender] < _value) revert(); if (balanceOf[_to] + _value < balanceOf[_to]) revert(); uint256 avp = 0; uint256 amount = 0; // Redeem tokens if ( _to == address(this) ) { /* Calc amount of ETH, divide on 10^9 because reedemPrice is multiplied for precision If the block number after 5000 from the last transaction to the contract, then redeem price is average price */ if ( lastTxBlockNum < (block.number-5000) ) { avp = this.balance * 1000000000 / totalSupply; amount = ( _value * avp ) / 1000000000; } else { amount = ( _value * redeemPrice ) / 1000000000; } balanceOf[msg.sender] -= _value; totalSupply -= _value; /* Calc new prices */ if ( totalSupply != 0 ) { avp = (this.balance-amount) * 1000000000 / totalSupply; redeemPrice = ( avp * 900 ) / 1000; // -10% tokenPrice = ( avp * 1100 ) / 1000; // +10% } else { redeemPrice = 0; tokenPrice = 100000000; } if (!msg.sender.send(amount)) revert(); Transfer(msg.sender, 0x0, _value); } else { balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } function approve(address _spender, uint256 _value) public returns(bool success) { allowance[msg.sender][_spender] = _value; return true; } function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { if (balanceOf[_from] < _value) revert(); if ((balanceOf[_to] + _value) < balanceOf[_to]) revert(); if (_value > allowance[_from][msg.sender]) revert(); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /* Payable function, calls when send ETHs to the contract */ function() internal payable { // If sent ETH value of transaction less than 10 Gwei then revert tran if ( msg.value < 10000000000 ) revert(); lastTxBlockNum = block.number; uint256 amount = ( msg.value / tokenPrice ) * 1000000000; balanceOf[msg.sender] += amount; totalSupply += amount; /* Calc new prices */ uint256 avp = this.balance * 1000000000 / totalSupply; redeemPrice = avp * 900 / 1000; // -10% tokenPrice = avp * 1100 / 1000; // +10% Transfer(0x0, msg.sender, amount); } }
/ This is ERC20 Token
contract upToken{ string public name; string public symbol; uint8 public decimals; string public standard = 'Token 0.1'; uint256 public totalSupply; The price at which tokens are sold tokenPrice is multiplied on 10^9 for precision tokenPrice 100000000 = 1 ETH per 10000 PNS uint256 public tokenPrice; The price at which the contract redeems tokens redeemPrice is multiplied on 10^9 for precision uint256 public redeemPrice; Last transaction block number uint256 public lastTxBlockNum; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); Contract constructor, this token with decimal = 18 and init price = 1 ETH This is an ERC20 token, an Ethereum based emulation of the Bitcoin ecosystem but with investor protection functions. The purpose of this token is to show how Bitcoin works and provide an even better investment opportunity than Ethereum other than by simply holding on to the coin itself. BUY: When you buy upTokens, your funds are stored in a contract and only you can retrieve them by sending upToken tokens back to the contract. SEND: You can send tokens to another Ethereum address. SELL: You can cash-out at any time and receive back the VALUE of the token, which is simply the exact share of all funds in the contract, less 10% discount. However, if there were no incoming transactions in the contract for the last 5,000 blocks (about 1 day) then you will receive your funds without a 10% discount. There are no pre mined supplies and upToken tokens are ONLY created in exchange for the ETH received. There is No chance to cheat on the system, No admin rights to the contract - No holes. The code is transparent and can be checked by everyone for validity and fairness. The price of the upToken is set in ETH and CANNOT GO DOWN! Every subsequent purchase transaction has a price that is slightly higher than the previous one. It is as SAFE as Ethereum, SECURE as Blockchain and as PROFITABLE as Bitcoin but with a LOWER RISK! The most you can loose is 10% which is the premium paid at the purchase, and even with a "panic sale" you can NEVER lose more than the 10% discount. If you wait, the VALUE of the upToken will grow with EVERY transaction. Whenever there is a purchase of upTokens, 10% from this is divided between ALL token owners, including you. When upTokens are sold early, the 10% discount is divided between ALL the remaining token owners. Every time someone sells upTokens for the true value, the value of the remained token stays the same! No rush to go out. As it is a valid ERC20 token, it can be traded and transferred without limitations. It can be listed on the exchanges. After the deployment, its future is in your hands - nobody can control the contract, except for all the token holders with their transactions. There are no administrators, no owners, no support and no possibility to be cheat on, it is a truly a decentralized autonomous system. The longer you stay, the BIGGER your share. You cannot be late to cash-out. Send ETH to this contract and upTokens will be sent in return with the same transaction to the wallet you sent ETH from. You should send only from your own wallet, not from an exchange's account. function upToken() public { name = "upToken"; symbol = "UPT"; decimals = 15; totalSupply = 0; tokenPrice = 100000000; } When you transfer tokens to the contract it redeem it by current redeemPrice Transfer tokens and redeem function transfer(address _to, uint256 _value) public { if (balanceOf[msg.sender] < _value) revert(); if (balanceOf[_to] + _value < balanceOf[_to]) revert(); uint256 avp = 0; uint256 amount = 0; if ( _to == address(this) ) { Calc amount of ETH, divide on 10^9 because reedemPrice is multiplied for precision If the block number after 5000 from the last transaction to the contract, then redeem price is average price if ( lastTxBlockNum < (block.number-5000) ) { avp = this.balance * 1000000000 / totalSupply; amount = ( _value * avp ) / 1000000000; amount = ( _value * redeemPrice ) / 1000000000; } balanceOf[msg.sender] -= _value; totalSupply -= _value; if ( totalSupply != 0 ) { avp = (this.balance-amount) * 1000000000 / totalSupply; redeemPrice = 0; tokenPrice = 100000000; } if (!msg.sender.send(amount)) revert(); Transfer(msg.sender, 0x0, _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } function transfer(address _to, uint256 _value) public { if (balanceOf[msg.sender] < _value) revert(); if (balanceOf[_to] + _value < balanceOf[_to]) revert(); uint256 avp = 0; uint256 amount = 0; if ( _to == address(this) ) { Calc amount of ETH, divide on 10^9 because reedemPrice is multiplied for precision If the block number after 5000 from the last transaction to the contract, then redeem price is average price if ( lastTxBlockNum < (block.number-5000) ) { avp = this.balance * 1000000000 / totalSupply; amount = ( _value * avp ) / 1000000000; amount = ( _value * redeemPrice ) / 1000000000; } balanceOf[msg.sender] -= _value; totalSupply -= _value; if ( totalSupply != 0 ) { avp = (this.balance-amount) * 1000000000 / totalSupply; redeemPrice = 0; tokenPrice = 100000000; } if (!msg.sender.send(amount)) revert(); Transfer(msg.sender, 0x0, _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } function transfer(address _to, uint256 _value) public { if (balanceOf[msg.sender] < _value) revert(); if (balanceOf[_to] + _value < balanceOf[_to]) revert(); uint256 avp = 0; uint256 amount = 0; if ( _to == address(this) ) { Calc amount of ETH, divide on 10^9 because reedemPrice is multiplied for precision If the block number after 5000 from the last transaction to the contract, then redeem price is average price if ( lastTxBlockNum < (block.number-5000) ) { avp = this.balance * 1000000000 / totalSupply; amount = ( _value * avp ) / 1000000000; amount = ( _value * redeemPrice ) / 1000000000; } balanceOf[msg.sender] -= _value; totalSupply -= _value; if ( totalSupply != 0 ) { avp = (this.balance-amount) * 1000000000 / totalSupply; redeemPrice = 0; tokenPrice = 100000000; } if (!msg.sender.send(amount)) revert(); Transfer(msg.sender, 0x0, _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } } else { Calc new prices function transfer(address _to, uint256 _value) public { if (balanceOf[msg.sender] < _value) revert(); if (balanceOf[_to] + _value < balanceOf[_to]) revert(); uint256 avp = 0; uint256 amount = 0; if ( _to == address(this) ) { Calc amount of ETH, divide on 10^9 because reedemPrice is multiplied for precision If the block number after 5000 from the last transaction to the contract, then redeem price is average price if ( lastTxBlockNum < (block.number-5000) ) { avp = this.balance * 1000000000 / totalSupply; amount = ( _value * avp ) / 1000000000; amount = ( _value * redeemPrice ) / 1000000000; } balanceOf[msg.sender] -= _value; totalSupply -= _value; if ( totalSupply != 0 ) { avp = (this.balance-amount) * 1000000000 / totalSupply; redeemPrice = 0; tokenPrice = 100000000; } if (!msg.sender.send(amount)) revert(); Transfer(msg.sender, 0x0, _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } } else { } else { function approve(address _spender, uint256 _value) public returns(bool success) { allowance[msg.sender][_spender] = _value; return true; } function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { if (balanceOf[_from] < _value) revert(); if ((balanceOf[_to] + _value) < balanceOf[_to]) revert(); if (_value > allowance[_from][msg.sender]) revert(); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } Payable function, calls when send ETHs to the contract function() internal payable { if ( msg.value < 10000000000 ) revert(); lastTxBlockNum = block.number; uint256 amount = ( msg.value / tokenPrice ) * 1000000000; balanceOf[msg.sender] += amount; totalSupply += amount; Calc new prices uint256 avp = this.balance * 1000000000 / totalSupply; Transfer(0x0, msg.sender, amount); } }
6,441,079
[ 1, 19, 1220, 353, 4232, 39, 3462, 3155, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 731, 1345, 95, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 533, 1071, 4529, 273, 296, 1345, 374, 18, 21, 13506, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 377, 203, 377, 202, 1986, 6205, 622, 1492, 2430, 854, 272, 1673, 203, 377, 202, 203, 377, 202, 2316, 5147, 353, 27789, 603, 1728, 66, 29, 364, 6039, 203, 1082, 203, 202, 202, 2316, 5147, 2130, 9449, 273, 404, 512, 2455, 1534, 12619, 453, 3156, 203, 565, 2254, 5034, 1071, 1147, 5147, 31, 203, 203, 202, 202, 1986, 6205, 622, 1492, 326, 6835, 283, 323, 7424, 2430, 203, 1082, 203, 202, 202, 266, 24903, 5147, 353, 27789, 603, 1728, 66, 29, 364, 6039, 6862, 203, 565, 2254, 5034, 1071, 283, 24903, 5147, 31, 203, 377, 203, 202, 202, 3024, 2492, 1203, 1300, 203, 565, 2254, 5034, 1071, 1142, 4188, 1768, 2578, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 377, 202, 8924, 3885, 16, 333, 1147, 598, 6970, 273, 6549, 471, 1208, 6205, 273, 404, 512, 2455, 203, 203, 2503, 353, 392, 4232, 39, 3462, 1147, 16, 392, 512, 18664, 379, 2 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // @Name SafeMath // @Desc Math operations with safety checks that throw on error // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // ---------------------------------------------------------------------------- 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) { return a / b; } 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; } } // ---------------------------------------------------------------------------- // @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 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 Basic token // @dev Basic version of StandardToken, with no allowances. // ---------------------------------------------------------------------------- contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } 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; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // ---------------------------------------------------------------------------- // @title Ownable // ---------------------------------------------------------------------------- contract Ownable { // Development Team Leader address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } // ---------------------------------------------------------------------------- // @title BlackList // @dev Base contract which allows children to implement an emergency stop mechanism. // ---------------------------------------------------------------------------- contract BlackList is Ownable { event Lock(address indexed LockedAddress); event Unlock(address indexed UnLockedAddress); mapping( address => bool ) public blackList; modifier CheckBlackList { require(blackList[msg.sender] != true); _; } function SetLockAddress(address _lockAddress) external onlyOwner returns (bool) { require(_lockAddress != address(0)); require(_lockAddress != owner); require(blackList[_lockAddress] != true); blackList[_lockAddress] = true; emit Lock(_lockAddress); return true; } function UnLockAddress(address _unlockAddress) external onlyOwner returns (bool) { require(blackList[_unlockAddress] != false); blackList[_unlockAddress] = false; emit Unlock(_unlockAddress); 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; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // ---------------------------------------------------------------------------- // @title Standard ERC20 token // @dev Implementation of the basic standard token. // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } 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; } 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; } } // ---------------------------------------------------------------------------- // @title MultiTransfer Token // @dev Only Admin // ---------------------------------------------------------------------------- contract MultiTransferToken is StandardToken, Ownable { function MultiTransfer(address[] _to, uint256[] _amount) onlyOwner public returns (bool) { require(_to.length == _amount.length); uint256 ui; uint256 amountSum = 0; for (ui = 0; ui < _to.length; ui++) { require(_to[ui] != address(0)); amountSum = amountSum.add(_amount[ui]); } require(amountSum <= balances[msg.sender]); for (ui = 0; ui < _to.length; ui++) { balances[msg.sender] = balances[msg.sender].sub(_amount[ui]); balances[_to[ui]] = balances[_to[ui]].add(_amount[ui]); emit Transfer(msg.sender, _to[ui], _amount[ui]); } return true; } } // ---------------------------------------------------------------------------- // @title Burnable Token // @dev Token that can be irreversibly burned (destroyed). // ---------------------------------------------------------------------------- contract BurnableToken is StandardToken, Ownable { event BurnAdminAmount(address indexed burner, uint256 value); function burnAdminAmount(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit BurnAdminAmount(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } } // ---------------------------------------------------------------------------- // @title Mintable token // @dev Simple ERC20 Token example, with mintable token creation // Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol // ---------------------------------------------------------------------------- contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier cannotMint() { require(mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // ---------------------------------------------------------------------------- // @title Pausable token // @dev StandardToken modified with pausable transfers. // ---------------------------------------------------------------------------- contract PausableToken is StandardToken, Pausable, BlackList { function transfer(address _to, uint256 _value) public whenNotPaused CheckBlackList returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused CheckBlackList returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused CheckBlackList returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused CheckBlackList returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused CheckBlackList returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // ---------------------------------------------------------------------------- // @title MyToken // @dev MyToken // ---------------------------------------------------------------------------- contract MyToken is StandardToken { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals, uint256 _initial_supply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply_ = _initial_supply; balances[msg.sender] = _initial_supply; } } contract UpgradableToken is MyToken, Ownable { StandardToken public functionBase; constructor() MyToken("Upgradable Token", "UGT", 18, 10e28) public { functionBase = new StandardToken(); } function setFunctionBase(address _base) onlyOwner public { require(_base != address(0) && functionBase != _base); functionBase = StandardToken(_base); } function transfer(address _to, uint256 _value) public returns (bool) { require(address(functionBase).delegatecall(0xa9059cbb, _to, _value)); return true; } } // ---------------------------------------------------------------------------- // @Project_CHARS(Smart_Charging_Platform) // @Creator_BICASlab([email protected]) // @Source_Code_Verification(Noah_Kim) // ---------------------------------------------------------------------------- contract CHARS is PausableToken, MintableToken, BurnableToken, MultiTransferToken { string public name = "CHARS"; string public symbol = "CHARSV3"; uint256 public decimals = 18; }
---------------------------------------------------------------------------- @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; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
1,174,099
[ 1, 5802, 7620, 225, 21800, 16665, 225, 3360, 6835, 1492, 5360, 2325, 358, 2348, 392, 801, 24530, 2132, 12860, 18, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21800, 16665, 353, 14223, 6914, 288, 203, 565, 871, 31357, 5621, 203, 565, 871, 1351, 19476, 5621, 203, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 203, 203, 565, 9606, 1347, 1248, 28590, 1435, 288, 2583, 12, 5, 8774, 3668, 1769, 389, 31, 289, 203, 565, 9606, 1347, 28590, 1435, 288, 2583, 12, 8774, 3668, 1769, 389, 31, 289, 203, 565, 445, 11722, 1435, 1338, 5541, 1347, 1248, 28590, 1071, 288, 203, 3639, 17781, 273, 638, 31, 203, 3639, 3626, 31357, 5621, 203, 565, 289, 203, 203, 565, 445, 640, 19476, 1435, 1338, 5541, 1347, 28590, 1071, 288, 203, 3639, 17781, 273, 629, 31, 203, 3639, 3626, 1351, 19476, 5621, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x861825daa0068136a55f6effb3f4a0b9aa17f51f //Contract name: Token //Balance: 0 Ether //Verification Date: 1/17/2018 //Transacion Count: 167 // CODE STARTS HERE // Copyright (c) 2017, 2018 EtherJack.io. All rights reserved. // This code is disclosed only to be used for inspection and audit purposes. // Code modification and use for any purpose other than security audit // is prohibited. Creation of derived works or unauthorized deployment // of the code or any its portion to a blockchain is prohibited. pragma solidity ^0.4.19; contract HouseOwned { address house; modifier onlyHouse { require(msg.sender == house); _; } /// @dev Contract constructor function HouseOwned() public { house = msg.sender; } } // SafeMath is a part of Zeppelin Solidity library // licensed under MIT License // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/LICENSE /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { // 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address _owner) public constant returns (uint balance); function allowance(address _owner, address _spender) public constant returns (uint remaining); function transfer(address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed tokenOwner, address indexed spender, uint value); } contract Token is HouseOwned, ERC20Interface { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public constant decimals = 0; uint256 public supply; // Trusted addresses Jackpot public jackpot; address public croupier; // All users' balances mapping (address => uint256) internal balances; // Users' deposits with Croupier mapping (address => uint256) public depositOf; // Total amount of deposits uint256 public totalDeposit; // Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier uint256 public frozenPool; // Allowance mapping mapping (address => mapping (address => uint256)) internal allowed; ////// /// @title Modifiers // /// @dev Only Croupier modifier onlyCroupier { require(msg.sender == croupier); _; } /// @dev Only Jackpot modifier onlyJackpot { require(msg.sender == address(jackpot)); _; } /// @dev Protection from short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } ////// /// @title Events // /// @dev Fired when a token is burned (bet made) event Burn(address indexed from, uint256 value); /// @dev Fired when a deposit is made or withdrawn /// direction == 0: deposit /// direction == 1: withdrawal event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit); /// @dev Fired when a deposit with Croupier is frozen (set for sale) event DepositFrozen(address indexed from, uint256 value); /// @dev Fired when a deposit with Croupier is unfrozen (removed from sale) // Value is the resulting deposit, NOT the unfrozen amount event DepositUnfrozen(address indexed from, uint256 value); ////// /// @title Constructor and Initialization // /// @dev Initializes contract with initial supply tokens to the creator of the contract function Token() HouseOwned() public { name = "JACK Token"; symbol = "JACK"; supply = 1000000; } /// @dev Function to set address of Jackpot contract once after creation /// @param _jackpot Address of the Jackpot contract function setJackpot(address _jackpot) onlyHouse public { require(address(jackpot) == 0x0); require(_jackpot != address(this)); // Protection from admin's mistake jackpot = Jackpot(_jackpot); uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses balances[house] = bountyPortion; // House receives the bounty tokens balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest croupier = jackpot.croupier(); } ////// /// @title Public Methods // /// @dev Croupier invokes this method to return deposits to players /// @param _to The address of the recipient /// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited function returnDeposit(address _to, uint256 _extra) onlyCroupier public { require(depositOf[_to] > 0 || _extra > 0); uint256 amount = depositOf[_to]; depositOf[_to] = 0; totalDeposit = totalDeposit.sub(amount); _transfer(croupier, _to, amount.add(_extra)); Deposit(_to, amount, 1, 0); } /// @dev Gets the balance of the specified address. /// @param _owner The address function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function totalSupply() public view returns (uint256) { return supply; } /// @dev Send `_value` tokens to `_to` /// @param _to The address of the recipient /// @param _value the amount to send function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(address(jackpot) != 0x0); require(croupier != 0x0); if (_to == address(jackpot)) { // It is a token bet. Ignoring _value, only using 1 token _burnFromAccount(msg.sender, 1); jackpot.betToken(msg.sender); return true; } if (_to == croupier && msg.sender != house) { // It's a deposit to Croupier. In addition to transferring the token, // mark it in the deposits table // House can't make deposits. If House is transferring something to // Croupier, it's just a transfer, nothing more depositOf[msg.sender] += _value; totalDeposit = totalDeposit.add(_value); Deposit(msg.sender, _value, 0, depositOf[msg.sender]); } // In all cases but Jackpot transfer (which is terminated by a return), actually // do perform the transfer return _transfer(msg.sender, _to, _value); } /// @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. /// @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. /// @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. /// @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; } /// @dev Croupier uses this method to set deposited credits of a player for sale /// @param _user The address of the user /// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested function freezeDeposit(address _user, uint256 _extra) onlyCroupier public { require(depositOf[_user] > 0 || _extra > 0); uint256 deposit = depositOf[_user]; depositOf[_user] = depositOf[_user].sub(deposit); totalDeposit = totalDeposit.sub(deposit); uint256 depositWithExtra = deposit.add(_extra); frozenPool = frozenPool.add(depositWithExtra); DepositFrozen(_user, depositWithExtra); } /// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit /// @param _user The user whose deposit is being unfrozen /// @param _value The value to unfreeze according to Croupier's records (off-chain sale data) function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public { require(_value > 0); require(frozenPool >= _value); depositOf[_user] = depositOf[_user].add(_value); totalDeposit = totalDeposit.add(_value); frozenPool = frozenPool.sub(_value); DepositUnfrozen(_user, depositOf[_user]); } /// @dev The Jackpot contract invokes this method when selling tokens from Croupier /// @param _to The recipient of the tokens /// @param _value The amount function transferFromCroupier(address _to, uint256 _value) onlyJackpot public { require(_value > 0); require(frozenPool >= _value); frozenPool = frozenPool.sub(_value); _transfer(croupier, _to, _value); } ////// /// @title Internal Methods // /// @dev Internal transfer function /// @param _from From address /// @param _to To address /// @param _value The value to transfer /// @return success function _transfer(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); // Prevent transfer to 0x0 address require(balances[_from] >= _value); // Check if the sender has enough balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); return true; } /// @dev Internal function for burning tokens /// @param _sender The token sender (whose tokens are being burned) /// @param _value The amount of tokens to burn function _burnFromAccount(address _sender, uint256 _value) internal { require(balances[_sender] >= _value); // Check if the sender has enough balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender supply = supply.sub(_value); // Updates totalSupply Burn(_sender, _value); } } contract Jackpot is HouseOwned { using SafeMath for uint; enum Stages { InitialOffer, // ICO stage: forming the jackpot fund GameOn, // The game is running GameOver, // The jackpot is won, paying out the jackpot Aborted // ICO aborted, refunding investments } uint256 constant initialIcoTokenPrice = 4 finney; uint256 constant initialBetAmount = 10 finney; uint constant gameStartJackpotThreshold = 333 ether; uint constant icoTerminationTimeout = 48 hours; // These variables hold the values needed for minor prize checking: // - when they were last won (once the number reaches the corresponding amount, the // minor prize is won, and it should be reset) // - how much ether was bet since it was last won // `etherSince*` variables start with value of 1 and always have +1 in their value // so that the variables never go 0, for gas consumption consistency uint32 public totalBets = 0; uint256 public etherSince20 = 1; uint256 public etherSince50 = 1; uint256 public etherSince100 = 1; uint256 public pendingEtherForCroupier = 0; // ICO status uint32 public icoSoldTokens; uint256 public icoEndTime; // Jackpot status address public lastBetUser; uint256 public terminationTime; address public winner; uint256 public pendingJackpotForHouse; uint256 public pendingJackpotForWinner; // General configuration and stage address public croupier; Token public token; Stages public stage = Stages.InitialOffer; // Price state uint256 public currentIcoTokenPrice = initialIcoTokenPrice; uint256 public currentBetAmount = initialBetAmount; // Investment tracking for emergency ICO termination mapping (address => uint256) public investmentOf; uint256 public abortTime; ////// /// @title Modifiers // /// @dev Only Token modifier onlyToken { require(msg.sender == address(token)); _; } /// @dev Only Croupier modifier onlyCroupier { require(msg.sender == address(croupier)); _; } ////// /// @title Events // /// @dev Fired when tokens are sold for Ether in ICO event EtherIco(address indexed from, uint256 value, uint256 tokens); /// @dev Fired when a bid with Ether is made event EtherBet(address indexed from, uint256 value, uint256 dividends); /// @dev Fired when a bid with a Token is made event TokenBet(address indexed from); /// @dev Fired when a bidder wins a minor prize /// Type: 1: 20, 2: 50, 3: 100 event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType); /// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool /// The parameters are who bought them, how many tokens, and for how much Ether they were sold event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens); /// @dev Fired when the jackpot is won event JackpotWon(address indexed from, uint256 value); ////// /// @title Constructor and Initialization // /// @dev The contract constructor /// @param _croupier The address of the trusted Croupier bot's account function Jackpot(address _croupier) HouseOwned() public { require(_croupier != 0x0); croupier = _croupier; // There are no bets (it even starts in ICO stage), so initialize // lastBetUser, just so that value is not zero and is meaningful // The game can't end until at least one bid is made, and once // a bid is made, this value is permanently overwritten. lastBetUser = _croupier; } /// @dev Function to set address of Token contract once after creation /// @param _token Address of the Token contract (JACK Token) function setToken(address _token) onlyHouse public { require(address(token) == 0x0); require(_token != address(this)); // Protection from admin's mistake token = Token(_token); } ////// /// @title Default Function // /// @dev The fallback function for receiving ether (bets) /// Action depends on stages: /// - ICO: just sell the tokens /// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes /// - Game Over: pay out jackpot /// - Aborted: fail function() payable public { require(croupier != 0x0); require(address(token) != 0x0); require(stage != Stages.Aborted); uint256 tokens; if (stage == Stages.InitialOffer) { // First, check if the ICO is over. If it is, trigger the events and // refund sent ether bool started = checkGameStart(); if (started) { // Refund ether without failing the transaction // (because side-effect is needed) msg.sender.transfer(msg.value); return; } require(msg.value >= currentIcoTokenPrice); // THE PLAN // 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is, // calculate how many tokens the investor is going to get // 2. [EFFECT] Log and count // 3. [EFFECT] Check game start conditions and maybe start the game // 4. [INT] Award the tokens // 5. [INT] Transfer 20% to house // 1. [CHECK + EFFECT] Checking the amount tokens = _icoTokensForEther(msg.value); // 2. [EFFECT] Log // Log the ICO event and count investment EtherIco(msg.sender, msg.value, tokens); investmentOf[msg.sender] = investmentOf[msg.sender].add( msg.value.sub(msg.value / 5) ); // 3. [EFFECT] Game start // Check if we have accumulated the jackpot amount required for game start if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) { icoEndTime = now + icoTerminationTimeout; } // 4. [INT] Awarding tokens // Award the deserved tokens (if any) if (tokens > 0) { token.transfer(msg.sender, tokens); } // 5. [INT] House // House gets 20% of ICO according to the rules house.transfer(msg.value / 5); } else if (stage == Stages.GameOn) { // First, check if the game is over. If it is, trigger the events and // refund sent ether bool terminated = checkTermination(); if (terminated) { // Refund ether without failing the transaction // (because side-effect is needed) msg.sender.transfer(msg.value); return; } // Now processing an Ether bid require(msg.value >= currentBetAmount); // THE PLAN // 1. [CHECK] Calculate how much times min-bet, the bet amount is, // calculate how many tokens the player is going to get // 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot // 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit) // 4. [EFFECT] Log and mark bid // 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes // 7. [EFFECT] Update bet amount // 8. [INT] Award the tokens // 1. [CHECK + EFFECT] Checking the bet amount and token reward tokens = _betTokensForEther(msg.value); // 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot // The priority is (1) Croupier, (2) Jackpot uint256 sellingFromJackpot = 0; uint256 sellingFromCroupier = 0; if (tokens > 0) { uint256 croupierPool = token.frozenPool(); uint256 jackpotPool = token.balanceOf(this); if (croupierPool == 0) { // Simple case: only Jackpot is selling sellingFromJackpot = tokens; if (sellingFromJackpot > jackpotPool) { sellingFromJackpot = jackpotPool; } } else if (jackpotPool == 0 || tokens <= croupierPool) { // Simple case: only Croupier is selling // either because Jackpot has 0, or because Croupier takes over // by priority and has enough tokens in its pool sellingFromCroupier = tokens; if (sellingFromCroupier > croupierPool) { sellingFromCroupier = croupierPool; } } else { // Complex case: both are selling now sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point sellingFromJackpot = tokens.sub(sellingFromCroupier); if (sellingFromJackpot > jackpotPool) { sellingFromJackpot = jackpotPool; } } } // 3. [EFFECT] Croupier deposit // Transfer a portion to the Croupier for dividend payout and house benefit // Dividends are a sum of: // + 25% of bet // + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment) // + 0% of price of tokens sold from Croupier // (that goes in SoldTokensFromCroupier instead) uint256 tokenValue = msg.value.sub(currentBetAmount); uint256 croupierSaleRevenue = 0; if (sellingFromCroupier > 0) { croupierSaleRevenue = tokenValue.div( sellingFromJackpot.add(sellingFromCroupier) ).mul(sellingFromCroupier); } uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue); uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2)); // 100% of money for selling from Croupier still goes to Croupier // so that it's later paid out to the selling user pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue)); // 4. [EFFECT] Log and mark bid // Log the bet with actual amount charged (value less change) EtherBet(msg.sender, msg.value, dividends); lastBetUser = msg.sender; terminationTime = now + _terminationDuration(); // If anything was sold from Croupier, log it appropriately if (croupierSaleRevenue > 0) { SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier); } // 5. [INT] Minor prizes // Check for winning minor prizes _checkMinorPrizes(msg.sender, currentBetAmount); // 6. [EFFECT] Update bet amount _updateBetAmount(); // 7. [INT] Awarding tokens if (sellingFromJackpot > 0) { token.transfer(msg.sender, sellingFromJackpot); } if (sellingFromCroupier > 0) { token.transferFromCroupier(msg.sender, sellingFromCroupier); } } else if (stage == Stages.GameOver) { require(msg.sender == winner || msg.sender == house); if (msg.sender == winner) { require(pendingJackpotForWinner > 0); uint256 winnersPay = pendingJackpotForWinner; pendingJackpotForWinner = 0; msg.sender.transfer(winnersPay); } else if (msg.sender == house) { require(pendingJackpotForHouse > 0); uint256 housePay = pendingJackpotForHouse; pendingJackpotForHouse = 0; msg.sender.transfer(housePay); } } } // Croupier will call this function when the jackpot is won // If Croupier fails to call the function for any reason, house and winner // still can claim their jackpot portion by sending ether to Jackpot function payOutJackpot() onlyCroupier public { require(winner != 0x0); if (pendingJackpotForHouse > 0) { uint256 housePay = pendingJackpotForHouse; pendingJackpotForHouse = 0; house.transfer(housePay); } if (pendingJackpotForWinner > 0) { uint256 winnersPay = pendingJackpotForWinner; pendingJackpotForWinner = 0; winner.transfer(winnersPay); } } ////// /// @title Public Functions // /// @dev View function to check whether the game should be terminated /// Used as internal function by checkTermination, as well as by the /// Croupier bot, to check whether it should call checkTermination /// @return Whether the game should be terminated by timeout function shouldBeTerminated() public view returns (bool should) { return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime; } /// @dev Check whether the game should be terminated, and if it should, terminate it /// @return Whether the game was terminated as the result function checkTermination() public returns (bool terminated) { if (shouldBeTerminated()) { stage = Stages.GameOver; winner = lastBetUser; // Flush amount due for Croupier immediately _flushEtherToCroupier(); // The rest should be claimed by the winner (except what house gets) JackpotWon(winner, this.balance); uint256 jackpot = this.balance; pendingJackpotForHouse = jackpot.div(5); pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse); return true; } return false; } /// @dev View function to check whether the game should be started /// Used as internal function by `checkGameStart`, as well as by the /// Croupier bot, to check whether it should call `checkGameStart` /// @return Whether the game should be started function shouldBeStarted() public view returns (bool should) { return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime; } /// @dev Check whether the game should be started, and if it should, start it /// @return Whether the game was started as the result function checkGameStart() public returns (bool started) { if (shouldBeStarted()) { stage = Stages.GameOn; return true; } return false; } /// @dev Bet 1 token in the game /// The token has already been burned having passed all checks, so /// just process the bet of 1 token function betToken(address _user) onlyToken public { // Token bets can only be accepted in the game stage require(stage == Stages.GameOn); bool terminated = checkTermination(); if (terminated) { return; } TokenBet(_user); lastBetUser = _user; terminationTime = now + _terminationDuration(); // Check for winning minor prizes _checkMinorPrizes(_user, 0); } /// @dev Allows House to terminate ICO as an emergency measure function abort() onlyHouse public { require(stage == Stages.InitialOffer); stage = Stages.Aborted; abortTime = now; } /// @dev In case the ICO is emergency-terminated by House, allows investors /// to pull back the investments function claimRefund() public { require(stage == Stages.Aborted); require(investmentOf[msg.sender] > 0); uint256 payment = investmentOf[msg.sender]; investmentOf[msg.sender] = 0; msg.sender.transfer(payment); } /// @dev In case the ICO was terminated, allows House to kill the contract in 2 months /// after the termination date function killAborted() onlyHouse public { require(stage == Stages.Aborted); require(now > abortTime + 60 days); selfdestruct(house); } ////// /// @title Internal Functions // /// @dev Get current bid timer duration /// @return duration The duration function _terminationDuration() internal view returns (uint256 duration) { return (5 + 19200 / (100 + totalBets)) * 1 minutes; } /// @dev Updates the current ICO price according to the rules function _updateIcoPrice() internal { uint256 newIcoTokenPrice = currentIcoTokenPrice; if (icoSoldTokens < 10000) { newIcoTokenPrice = 4 finney; } else if (icoSoldTokens < 20000) { newIcoTokenPrice = 5 finney; } else if (icoSoldTokens < 30000) { newIcoTokenPrice = 5.3 finney; } else if (icoSoldTokens < 40000) { newIcoTokenPrice = 5.7 finney; } else { newIcoTokenPrice = 6 finney; } if (newIcoTokenPrice != currentIcoTokenPrice) { currentIcoTokenPrice = newIcoTokenPrice; } } /// @dev Updates the current bid price according to the rules function _updateBetAmount() internal { uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney; if (newBetAmount != currentBetAmount) { currentBetAmount = newBetAmount; } } /// @dev Calculates how many tokens a user should get with a given Ether bid /// @param value The bid amount /// @return tokens The number of tokens function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) { // One bet amount is for the bet itself, for the rest we will sell // tokens tokens = (value / currentBetAmount) - 1; if (tokens >= 1000) { tokens = tokens + tokens / 4; // +25% } else if (tokens >= 300) { tokens = tokens + tokens / 5; // +20% } else if (tokens >= 100) { tokens = tokens + tokens / 7; // ~ +14.3% } else if (tokens >= 50) { tokens = tokens + tokens / 10; // +10% } else if (tokens >= 20) { tokens = tokens + tokens / 20; // +5% } } /// @dev Calculates how many tokens a user should get with a given ICO transfer /// @param value The transfer amount /// @return tokens The number of tokens function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) { // How many times the input is greater than current token price tokens = value / currentIcoTokenPrice; if (tokens >= 10000) { tokens = tokens + tokens / 4; // +25% } else if (tokens >= 5000) { tokens = tokens + tokens / 5; // +20% } else if (tokens >= 1000) { tokens = tokens + tokens / 7; // ~ +14.3% } else if (tokens >= 500) { tokens = tokens + tokens / 10; // +10% } else if (tokens >= 200) { tokens = tokens + tokens / 20; // +5% } // Checking if Jackpot has the tokens in reserve if (tokens > token.balanceOf(this)) { tokens = token.balanceOf(this); } icoSoldTokens += (uint32)(tokens); _updateIcoPrice(); } /// @dev Flush the currently pending Ether to Croupier function _flushEtherToCroupier() internal { if (pendingEtherForCroupier > 0) { uint256 willTransfer = pendingEtherForCroupier; pendingEtherForCroupier = 0; croupier.transfer(willTransfer); } } /// @dev Count the bid towards minor prize fund, check if the user /// wins a minor prize, and if they did, transfer the prize to them /// @param user The user in question /// @param value The bid value function _checkMinorPrizes(address user, uint256 value) internal { // First and foremost, increment the counters and ether counters totalBets ++; if (value > 0) { etherSince20 = etherSince20.add(value); etherSince50 = etherSince50.add(value); etherSince100 = etherSince100.add(value); } // Now actually check if the bets won uint256 etherPayout; if ((totalBets + 30) % 100 == 0) { // Won 100th etherPayout = (etherSince100 - 1) / 10; etherSince100 = 1; MinorPrizePayout(user, etherPayout, 3); user.transfer(etherPayout); return; } if ((totalBets + 5) % 50 == 0) { // Won 100th etherPayout = (etherSince50 - 1) / 10; etherSince50 = 1; MinorPrizePayout(user, etherPayout, 2); user.transfer(etherPayout); return; } if (totalBets % 20 == 0) { // Won 20th etherPayout = (etherSince20 - 1) / 10; etherSince20 = 1; _flushEtherToCroupier(); MinorPrizePayout(user, etherPayout, 1); user.transfer(etherPayout); return; } return; } }
@dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
15,810,080
[ 1, 42, 2921, 1347, 279, 9949, 598, 512, 1136, 353, 7165, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 512, 1136, 38, 278, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 16, 2254, 5034, 3739, 350, 5839, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.safeApprove(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.underlyingTokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } }
* @title GeneralizedSwapMigrator @notice This contract is responsible for migration liquidity between pools Users can use this contract to remove their liquidity from the old pools and add them to the new ones with a single transaction./
contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } } catch { function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } } catch { migrationMap[oldPoolAddress] = mData; mData.oldPoolLPTokenAddress.safeApprove(oldPoolAddress, MAX_UINT256); function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolUnderlyingToken; try ISwap(oldPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { oldPoolUnderlyingToken = address(underlyingToken); require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolUnderlyingToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns ( IERC20 underlyingToken ) { require( oldPoolUnderlyingToken == address(underlyingToken), "Failed to match tokens list" ); require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolUnderlyingToken == address(0), "Failed to match tokens list" ); break; } } for (uint256 i = 0; i < mData.underlyingTokens.length; i++) { mData.underlyingTokens[i].safeApprove( mData.newPoolAddress, MAX_UINT256 ); } emit AddMigrationData(oldPoolAddress, mData); } function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } }
5,478,320
[ 1, 12580, 1235, 12521, 25483, 639, 225, 1220, 6835, 353, 14549, 364, 6333, 4501, 372, 24237, 3086, 16000, 12109, 848, 999, 333, 6835, 358, 1206, 3675, 4501, 372, 24237, 628, 326, 1592, 16000, 471, 527, 2182, 358, 326, 394, 5945, 598, 279, 2202, 2492, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9544, 1235, 12521, 25483, 639, 353, 14223, 6914, 16, 3360, 38, 6053, 4497, 429, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 1958, 15309, 751, 288, 203, 3639, 1758, 394, 2864, 1887, 31, 203, 3639, 467, 654, 39, 3462, 1592, 2864, 14461, 1345, 1887, 31, 203, 3639, 467, 654, 39, 3462, 394, 2864, 14461, 1345, 1887, 31, 203, 3639, 467, 654, 39, 3462, 8526, 6808, 5157, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 57, 3217, 5034, 273, 576, 636, 5034, 300, 404, 31, 203, 565, 2874, 12, 2867, 516, 15309, 751, 13, 1071, 6333, 863, 31, 203, 203, 565, 871, 1436, 10224, 751, 12, 2867, 8808, 1592, 2864, 1887, 16, 15309, 751, 312, 751, 1769, 203, 565, 871, 26507, 12, 203, 3639, 1758, 8808, 30188, 16, 203, 3639, 1758, 8808, 1592, 2864, 1887, 16, 203, 3639, 2254, 5034, 1592, 14461, 1345, 6275, 16, 203, 3639, 2254, 5034, 394, 14461, 1345, 6275, 203, 565, 11272, 203, 203, 203, 565, 3885, 1435, 1071, 14223, 6914, 1435, 2618, 203, 565, 445, 527, 10224, 751, 12, 203, 3639, 1758, 1592, 2864, 1887, 16, 203, 3639, 15309, 751, 3778, 312, 751, 16, 203, 3639, 1426, 6156, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 309, 16051, 19274, 13, 288, 203, 5411, 2583, 12, 203, 7734, 1758, 12, 15746, 863, 63, 1673, 2864, 1887, 8009, 1673, 2864, 14461, 1345, 1887, 13, 422, 203, 10792, 1758, 12, 20, 3631, 203, 7734, 315, 12892, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import "./DiamondStorageContract.sol"; import "./DiamondHeaders.sol"; import "./DiamondFacet.sol"; import "./WonkaEngineStructs.sol"; import "./WonkaEngineSupportFacet.sol"; import "./WonkaEngineDiamond.sol"; import "./TransactionStateInterface.sol"; /// @title An Ethereum library that contains the functionality for a rules engine /// @author Aaron Kendall /// @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs /// @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library contract WonkaEngineMainFacet is DiamondFacet { /// @dev Defines an event that will report when a ruletree has been invoked to validate a provided record. /// @author Aaron Kendall /// @notice event CallRuleTree( address indexed ruler ); /// @dev Defines an event that will report when a ruleset has been invoked when validating a provided record. /// @author Aaron Kendall /// @notice event CallRuleSet( address indexed ruler, bytes32 indexed tmpRuleSetId ); /// @dev Defines an event that will report when a rule has been invoked when validating a provided record. /// @author Aaron Kendall /// @notice event CallRule( address indexed ruler, bytes32 indexed ruleSetId, bytes32 indexed ruleId, uint ruleType ); /// @dev Defines an event that will report when the record does not satisfy a ruleset. /// @author Aaron Kendall event RuleSetError ( address indexed ruler, bytes32 indexed ruleSetId, bool severeFailure ); uint constant CONST_CUSTOM_OP_ARGS = 4; string constant blankValue = ""; // An enum for the type of rules currently supported enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, Populated, InDomain, Assign, OpAdd, OpSub, OpMult, OpDiv, CustomOp, MAX_TYPE } RuleTypes constant defaultType = RuleTypes.IsEqual; bool lastTransactionSuccess; bool orchestrationMode; bytes32 defaultTargetSource; // The cache of records that are owned by "rulers" and that are validated when invoking a rule tree mapping(address => mapping(bytes32 => string)) public currentRecords; WonkaEngineDiamond diamond; /// @dev Constructor for the main facet /// @author Aaron Kendall constructor() public { lastTransactionSuccess = false; orchestrationMode = false; } modifier onlyEngineOwner() { require(msg.sender == diamond.rulesMaster(), "The caller of this method does not have permission for this action."); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } modifier onlyEngineOwnerOrTreeOwner(address _RTOwner) { require((msg.sender == diamond.rulesMaster()) || (msg.sender == _RTOwner), "The caller of this method does not have permission for this action."); require(diamond.hasRuleTree(_RTOwner) == true, "The specified RuleTree does not exist."); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } /// @dev This method will set the address for the Wonka Diamond (proxy) /// @author Aaron Kendall function setDiamondAddress(address payable _diamondAddress, address ruler) public onlyEngineOwnerOrTreeOwner(ruler) { require(msg.sender == diamond.rulesMaster(), "The caller of this method does not have permission for this action."); diamond = WonkaEngineDiamond(_diamondAddress); } /// @dev This method will invoke the ruler's RuleTree in order to validate their stored record. This method should be invoked via a call() and not a transaction(). /// @author Aaron Kendall /// @notice This method will only return a boolean function execute(address ruler) public onlyEngineOwnerOrTreeOwner(ruler) returns (bool executeSuccess) { executeSuccess = true; // NOTE: Is this necessary? // require(ruletrees[ruler].allRuleSetList.length > 0, "The specified RuleTree is empty."); // NOTE: Is this necessary? // require(ruletrees[ruler].rootRuleSetName != "", "The specified RuleTree has an invalid root."); emit CallRuleTree(ruler); (, , bytes32 rootRSID, uint totalRuleNum) = diamond.getRuleTreeProps(ruler); WonkaEngineStructs.WonkaRuleReport memory report = WonkaEngineStructs.WonkaRuleReport({ ruleFailCount: 0, ruleSetIds: new bytes32[](totalRuleNum), ruleIds: new bytes32[](totalRuleNum) }); // NOTE: These methods need to be altered for the storage executeWithReport(ruler, rootRSID, report); executeSuccess = lastTransactionSuccess = (report.ruleFailCount == 0); } /// @dev This method will invoke one RuleSet within a RuleTree when validating a stored record /// @author Aaron Kendall /// @notice This method will return a boolean that assists with traversing the RuleTree function executeWithReport(address ruler, bytes32 rsId, WonkaEngineStructs.WonkaRuleReport memory ruleReport) private returns (bool executeSuccess) { executeSuccess = true; emit CallRuleSet(ruler, targetRuleSet.ruleSetId); (, bool severeFailure, bool useAndOp, uint evalRuleCount, uint assertiveRuleCount, uint childRSCount) = diamond.getRuleSetProps(ruler, rsId); bool tempResult = false; bool tempSetResult = true; /** ** NOTE: These methods need to be altered for the storage ** if (transStateInd[ruletrees[ruler].ruleTreeId]) { require(transStateMap[ruletrees[ruler].ruleTreeId].isTransactionConfirmed(), "Transaction has not been confirmed."); require(transStateMap[ruletrees[ruler].ruleTreeId].isExecutor(ruler), "Sender is not a permitted executor."); } bool failImmediately = targetRuleSet.failImmediately; // Now invoke the rules for (uint idx = 0; idx < targetRuleSet.evalRuleList.length; idx++) { WonkaRule storage tempRule = targetRuleSet.evaluativeRules[targetRuleSet.evalRuleList[idx]]; tempResult = executeWithReport(ruler, tempRule, ruleReport); if (failImmediately) require(tempResult); if (idx == 0) { tempSetResult = tempResult; } else { if (useAndOp) tempSetResult = (tempSetResult && tempResult); else tempSetResult = (tempSetResult || tempResult); } } executeSuccess = tempSetResult; if (!executeSuccess) { emit RuleSetError(ruler, targetRuleSet.ruleSetId, severeFailure); } if (targetRuleSet.isLeaf && severeFailure) return executeSuccess; if (executeSuccess && (targetRuleSet.childRuleSetList.length > 0)) { // Now invoke the rulesets for (uint rsIdx = 0; rsIdx < targetRuleSet.childRuleSetList.length; rsIdx++) { tempResult = executeWithReport(ruler, ruletrees[ruler].allRuleSets[targetRuleSet.childRuleSetList[rsIdx]], ruleReport); executeSuccess = (executeSuccess && tempResult); } } else executeSuccess = true; // NOTE: Should the transaction state be reset automatically upon the completion of the transaction? //if (transStateInd[ruletrees[ruler].ruleTreeId]) { // transStateMap[ruletrees[ruler].ruleTreeId].revokeAllConfirmations(); //} **/ } /// @dev This method will invoke one Rule within a RuleSet when validating a stored record /// @author Aaron Kendall /// @notice This method will return a boolean that assists with traversing the RuleTree function executeRuleWithReport(address ruler, WonkaEngineStructs.WonkaRule storage targetRule, WonkaEngineStructs.WonkaRuleReport memory ruleReport) private returns (bool ruleResult) { ruleResult = true; bool almostOpInd = false; uint testNumValue = 0; uint ruleNumValue = 0; string memory tempValue = getValueOnRecord(ruler, targetRule.targetAttr.attrName); // NOTE: USE WHEN DEBUGGING IS NEEDED emit CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType); if (targetRule.targetAttr.isNumeric) { testNumValue = parseInt(tempValue, 0); ruleNumValue = parseInt(targetRule.ruleValue, 0); // NOTE: Too expensive to deploy? // if (keccak256(abi.encodePacked(targetRule.ruleValue)) != keccak256(abi.encodePacked("NOW"))) { // This indicates that we are doing a timestamp comparison with the value for NOW (and maybe looking for a window of one day ahead) if (targetRule.targetAttr.isString && targetRule.targetAttr.isNumeric && (ruleNumValue <= 1)) { if (ruleNumValue == 1) { almostOpInd = true; } ruleNumValue = block.timestamp + (ruleNumValue * 1 days); } // This indicates that we are doing a block number comparison (i.e., the hex number is the keccak256() result for the string "BLOCKNUMOP") else if (keccak256(abi.encodePacked(targetRule.ruleValue)) == keccak256(abi.encodePacked("00000"))) { ruleNumValue = block.number; } } if (almostOpInd) { ruleResult = ((testNumValue > block.timestamp) && (testNumValue < ruleNumValue)); } else if (uint(RuleTypes.IsEqual) == targetRule.ruleType) { if (targetRule.targetAttr.isNumeric) { ruleResult = (testNumValue == ruleNumValue); } else { ruleResult = (keccak256(abi.encodePacked(tempValue)) == keccak256(abi.encodePacked(targetRule.ruleValue))); } } else if (uint(RuleTypes.IsLessThan) == targetRule.ruleType) { if (targetRule.targetAttr.isNumeric) ruleResult = (testNumValue < ruleNumValue); } else if (uint(RuleTypes.IsGreaterThan) == targetRule.ruleType) { if (targetRule.targetAttr.isNumeric) ruleResult = (testNumValue > ruleNumValue); } else if (uint(RuleTypes.Populated) == targetRule.ruleType) { ruleResult = (keccak256(abi.encodePacked(tempValue)) != keccak256(abi.encodePacked(""))); } else if (uint(RuleTypes.InDomain) == targetRule.ruleType) { ruleResult = (keccak256(abi.encodePacked(targetRule.ruleValueDomain[tempValue])) == keccak256(abi.encodePacked("Y"))); } else if (uint(RuleTypes.Assign) == targetRule.ruleType) { setValueOnRecord(ruler, targetRule.targetAttr.attrName, targetRule.ruleValue); } else if ( (uint(RuleTypes.OpAdd) == targetRule.ruleType) || (uint(RuleTypes.OpSub) == targetRule.ruleType) || (uint(RuleTypes.OpMult) == targetRule.ruleType) || (uint(RuleTypes.OpDiv) == targetRule.ruleType) ) { uint calculatedValue = calculateValue(ruler, targetRule); string memory convertedValue = ""; DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.bytes32ToString.selector])); bytes memory BTSFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.bytes32ToString.selector, uintToBytes(calculatedValue)); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(BTSFunction); require(success); (convertedValue) = abi.decode(returnedData, (string)); setValueOnRecord(ruler, targetRule.targetAttr.attrName, convertedValue); } else if (uint(RuleTypes.CustomOp) == targetRule.ruleType) { bytes32 customOpName = ""; string memory customOpResult = ""; if (targetRule.ruleDomainKeys.length > 0) customOpName = stringToBytes32(targetRule.ruleDomainKeys[0]); bytes32[] memory argsDomain = new bytes32[](CONST_CUSTOM_OP_ARGS); for (uint idx = 0; idx < CONST_CUSTOM_OP_ARGS; ++idx) { if (idx < targetRule.customOpArgs.length) argsDomain[idx] = stringToBytes32(determineDomainValue(ruler, idx, targetRule)); else argsDomain[idx] = ""; } DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.invokeCustomOperator.selector])); bytes memory ICPFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.invokeCustomOperator.selector, diamond.getCustomOp(customOpName).contractAddress, ruler, diamond.getCustomOp(customOpName).methodName, argsDomain[0], argsDomain[1], argsDomain[2], argsDomain[3]); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(ICPFunction); require(success); (customOpResult) = abi.decode(returnedData, (string)); // string memory customOpResult = invokeCustomOperator(opMap[customOpName].contractAddress, ruler, opMap[customOpName].methodName, argsDomain[0], argsDomain[1], argsDomain[2], argsDomain[3]); setValueOnRecord(ruler, targetRule.targetAttr.attrName, customOpResult); } if (!ruleResult && diamond.isLeaf(ruler,targetRule.parentRuleSetId)) { // NOTE: USE WHEN DEBUGGING IS NEEDED emit CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType); ruleReport.ruleSetIds[ruleReport.ruleFailCount] = targetRule.parentRuleSetId; ruleReport.ruleIds[ruleReport.ruleFailCount] = targetRule.name; ruleReport.ruleFailCount += 1; } } /** ** NOTE: These methods need to be altered for the storage ** /// @dev This method will return the report generated by the engine's last execution /// @author Aaron Kendall function getLastRuleReport() public view returns (uint fails, bytes32[] memory rsets, bytes32[] memory rules) { return (lastRuleReport.ruleFailCount, lastRuleReport.ruleSetIds, lastRuleReport.ruleIds); } **/ /// @dev This method will return the indicator of whether or not the last execuction of the engine was a validation success /// @author Aaron Kendall function getLastTransactionSuccess() public view returns(bool) { return lastTransactionSuccess; } /// @dev This method will return the value for an Attribute that is currently stored within the ruler's record /// @author Aaron Kendall /// @notice This method should only be used for debugging purposes. function getValueOnRecord(address ruler, bytes32 key) public onlyEngineOwnerOrTreeOwner(ruler) returns(string memory) { require (diamond.isAttribute(key), "The specified Attribute does not exist."); if (!orchestrationMode) { return (currentRecords[ruler])[key]; } else { string memory recordValue = blankValue; DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.invokeValueRetrieval.selector])); if (diamond.getSource(key).isValue) { bytes memory IVRFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.invokeValueRetrieval.selector, diamond.getSource(key).contractAddress, ruler, diamond.getSource(key).methodName, key); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(IVRFunction); require(success); (recordValue) = abi.decode(returnedData, (string)); } else if (diamond.getSource(defaultTargetSource).isValue){ bytes memory IVRFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.invokeValueRetrieval.selector, diamond.getSource(defaultTargetSource).contractAddress, ruler, diamond.getSource(defaultTargetSource).methodName, key); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(IVRFunction); require(success); (recordValue) = abi.decode(returnedData, (string)); } return recordValue; } } /// @dev This method will indicate whether or not a particular source exists /// @author Aaron Kendall /// @notice This method should only be used for debugging purposes. function getIsSourceMapped(bytes32 key) public view returns(bool) { return diamond.getSource(key).isValue; } /// @dev This method will indicate whether or not the Orchestration mode has been enabled /// @author Aaron Kendall /// @notice This method should only be used for debugging purposes. function getOrchestrationMode() public view returns(bool) { return orchestrationMode; } /// @dev This method will set the flag as to whether or not the engine should run in Orchestration mode (i.e., use the sourceMap) /// @author Aaron Kendall function setOrchestrationMode(bool orchMode, bytes32 defSource) public onlyEngineOwner { orchestrationMode = orchMode; defaultTargetSource = defSource; } /// @dev This method will set an Attribute value on the record associated with the provided address/account /// @author Aaron Kendall /// @notice We do not currently check here to see if the value qualifies according to the Attribute's definition function setValueOnRecord(address ruler, bytes32 key, string memory value) public returns(string memory) { require(diamond.hasRuleTree(ruler), "The provided user does not own anything on this instance of the contract."); require(diamond.isAttribute(key), "The specified Attribute does not exist."); if (!orchestrationMode) { (currentRecords[ruler])[key] = value; return (currentRecords[ruler])[key]; } else { DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.parseInt.selector])); bytes32 bytes32Value = ""; bytes32 targetKey = ""; string memory retValue = ""; bytes memory STBFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.stringToBytes32.selector, value); (bool successSTB, bytes memory returnedDataSTB) = address(supportFacetAddress).delegatecall(STBFunction); require(successSTB); (bytes32Value) = abi.decode(returnedDataSTB, (bytes32)); if (diamond.getSource(key).isValue && (keccak256(abi.encodePacked(diamond.getSource(key).setMethodName)) != keccak256(abi.encodePacked("")))) { targetKey = key; } else if (diamond.getSource(defaultTargetSource).isValue && (keccak256(abi.encodePacked(diamond.getSource(defaultTargetSource).setMethodName)) != keccak256(abi.encodePacked("")))) { targetKey = defaultTargetSource; } if (targetKey != "") { bytes memory IVSFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.invokeValueSetter.selector, diamond.getSource(targetKey).contractAddress, ruler, diamond.getSource(targetKey).setMethodName, key, bytes32Value); (bool successIVS, bytes memory returnedDataIVS) = address(supportFacetAddress).delegatecall(IVSFunction); require(successIVS); (retValue) = abi.decode(returnedDataIVS, (string)); } return retValue; } } // SUPPORT METHODS /// @dev This method will calculate the value for a Rule according to its type (Add, Subtract, etc.) and its domain values /// @notice function calculateValue(address ruler, WonkaEngineStructs.WonkaRule storage targetRule) private returns (uint calcValue){ uint tmpValue = 0; uint finalValue = 0; for (uint i = 0; i < targetRule.ruleDomainKeys.length; i++) { bytes32 keyName = stringToBytes32(targetRule.ruleDomainKeys[i]); if (diamond.isAttribute(keyName)) tmpValue = parseInt(getValueOnRecord(ruler, keyName), 0); else tmpValue = parseInt(targetRule.ruleDomainKeys[i], 0); if (i == 0) finalValue = tmpValue; else { if ( uint(RuleTypes.OpAdd) == targetRule.ruleType ) finalValue += tmpValue; else if ( uint(RuleTypes.OpSub) == targetRule.ruleType ) finalValue -= tmpValue; else if ( uint(RuleTypes.OpMult) == targetRule.ruleType ) finalValue *= tmpValue; else if ( uint(RuleTypes.OpDiv) == targetRule.ruleType ) finalValue /= tmpValue; } } calcValue = finalValue; } /// @author Aaron Kendall /// @dev This method will assist by returning the correct value, either a literal static value or one obtained through retrieval function determineDomainValue(address ruler, uint domainIdx, WonkaEngineStructs.WonkaRule storage targetRule) private returns (string memory retValue) { bytes32 keyName = targetRule.customOpArgs[domainIdx]; if (diamond.isAttribute(keyName)) { retValue = getValueOnRecord(ruler, keyName); } else { // NOTE: OLD WAY // retValue = bytes32ToString(keyName); // NOTE: ALT WAY // (bool success, bytes memory retData) = address(diamond).call(bytes4(bytes32(keccak256("bytes32ToString(bytes32)"))), keyName); // (uint a, uint[2] memory b, bytes memory c) = abi.decode(retData, (uint, uint[2], bytes)) // (retValue) = abi.decode(retData, (string)); DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.bytes32ToString.selector])); bytes memory BTSFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.bytes32ToString.selector, keyName); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(BTSFunction); require(success); (retValue) = abi.decode(returnedData, (string)); } } /// @dev This method will convert a 'string' type to a 'uint' type function parseInt(string memory _a, uint _b) public returns (uint retValue) { DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.parseInt.selector])); bytes memory PIFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.parseInt.selector, _a, _b); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(PIFunction); require(success); (retValue) = abi.decode(returnedData, (uint)); return retValue; } /// @dev This method will convert a 'string' type to a 'bytes32' type function stringToBytes32(string memory source) public returns (bytes32 result) { DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.stringToBytes32.selector])); bytes memory STBFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.stringToBytes32.selector, source); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(STBFunction); require(success); (result) = abi.decode(returnedData, (bytes32)); return result; } /// @dev This method will convert a 'uint' type to a 'bytes32' type function uintToBytes(uint targetVal) private returns (bytes32 retValue) { DiamondStorage storage ds = diamondStorage(); address supportFacetAddress = address(bytes20(ds.facets[WonkaEngineSupportFacet.uintToBytes.selector])); bytes memory UTBFunction = abi.encodeWithSelector(WonkaEngineSupportFacet.uintToBytes.selector, targetVal); (bool success, bytes memory returnedData) = address(supportFacetAddress).delegatecall(UTBFunction); require(success); (retValue) = abi.decode(returnedData, (bytes32)); return retValue; } }
@dev This method will set the address for the Wonka Diamond (proxy) @author Aaron Kendall
function setDiamondAddress(address payable _diamondAddress, address ruler) public onlyEngineOwnerOrTreeOwner(ruler) { require(msg.sender == diamond.rulesMaster(), "The caller of this method does not have permission for this action."); diamond = WonkaEngineDiamond(_diamondAddress); }
5,490,981
[ 1, 2503, 707, 903, 444, 326, 1758, 364, 326, 678, 265, 7282, 12508, 301, 1434, 261, 5656, 13, 225, 432, 297, 265, 1475, 409, 454, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 14521, 301, 1434, 1887, 12, 2867, 8843, 429, 389, 3211, 301, 1434, 1887, 16, 1758, 436, 17040, 13, 1071, 1338, 4410, 5541, 1162, 2471, 5541, 12, 86, 17040, 13, 288, 203, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4314, 301, 1434, 18, 7482, 7786, 9334, 315, 1986, 4894, 434, 333, 707, 1552, 486, 1240, 4132, 364, 333, 1301, 1199, 1769, 203, 203, 3639, 4314, 301, 1434, 273, 678, 265, 7282, 4410, 14521, 301, 1434, 24899, 3211, 301, 1434, 1887, 1769, 203, 565, 289, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa1a5143b4044cC3B710FfB8D7130b24a542536f0/sources/lib/forge-std/src/safeconsole.sol
Selector of `log(uint256,bool,uint256,uint256)`.
function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure { bytes32 m0; bytes32 m1; bytes32 m2; bytes32 m3; bytes32 m4; assembly { m0 := mload(0x00) m1 := mload(0x20) m2 := mload(0x40) m3 := mload(0x60) m4 := mload(0x80) mstore(0x00, 0xc6acc7a8) mstore(0x20, p0) mstore(0x40, p1) mstore(0x60, p2) mstore(0x80, p3) } _sendLogPayload(0x1c, 0x84); assembly { mstore(0x00, m0) mstore(0x20, m1) mstore(0x40, m2) mstore(0x60, m3) mstore(0x80, m4) } }
16,053,217
[ 1, 4320, 434, 1375, 1330, 12, 11890, 5034, 16, 6430, 16, 11890, 5034, 16, 11890, 5034, 13, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 613, 12, 11890, 5034, 293, 20, 16, 1426, 293, 21, 16, 2254, 5034, 293, 22, 16, 2254, 5034, 293, 23, 13, 2713, 16618, 288, 203, 3639, 1731, 1578, 312, 20, 31, 203, 3639, 1731, 1578, 312, 21, 31, 203, 3639, 1731, 1578, 312, 22, 31, 203, 3639, 1731, 1578, 312, 23, 31, 203, 3639, 1731, 1578, 312, 24, 31, 203, 3639, 19931, 288, 203, 5411, 312, 20, 519, 312, 945, 12, 20, 92, 713, 13, 203, 5411, 312, 21, 519, 312, 945, 12, 20, 92, 3462, 13, 203, 5411, 312, 22, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 312, 23, 519, 312, 945, 12, 20, 92, 4848, 13, 203, 5411, 312, 24, 519, 312, 945, 12, 20, 92, 3672, 13, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 374, 6511, 26, 8981, 27, 69, 28, 13, 203, 5411, 312, 2233, 12, 20, 92, 3462, 16, 293, 20, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 293, 21, 13, 203, 5411, 312, 2233, 12, 20, 92, 4848, 16, 293, 22, 13, 203, 5411, 312, 2233, 12, 20, 92, 3672, 16, 293, 23, 13, 203, 3639, 289, 203, 3639, 389, 4661, 1343, 6110, 12, 20, 92, 21, 71, 16, 374, 92, 5193, 1769, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 312, 20, 13, 203, 5411, 312, 2233, 12, 20, 92, 3462, 16, 312, 21, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 312, 22, 13, 203, 5411, 312, 2233, 12, 2 ]
pragma solidity ^0.4.19; // File: contracts/zeppelin/math/SafeMath.sol /** * @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; } } // File: contracts/zeppelin/token/ERC20/ERC20Basic.sol /** * @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); } // File: contracts/zeppelin/token/ERC20/BasicToken.sol /** * @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]); // 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]; } } // File: contracts/zeppelin/token/ERC20/ERC20.sol /** * @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); } // File: contracts/zeppelin/token/ERC20/StandardToken.sol /** * @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); 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; } } // File: contracts/zeppelin/ownership/Ownable.sol /** * @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); _; } /** * @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; } } // File: contracts/ico/Recoverable.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ pragma solidity ^0.4.12; contract Recoverable is Ownable { /// @dev Empty constructor (for now) function Recoverable() public { } /// @dev This will be invoked by the owner, when owner wants to rescue tokens /// @param token Token which will we rescue to the owner from the contract function recoverTokens(ERC20Basic token) onlyOwner public { token.transfer(owner, tokensToBeReturned(token)); } /// @dev Interface function, can be overwritten by the superclass /// @param token Token which balance we will check and return /// @return The amount of tokens (in smallest denominator) the contract owns function tokensToBeReturned(ERC20Basic token) public returns (uint) { return token.balanceOf(this); } } // File: contracts/ico/StandardTokenExt.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ pragma solidity ^0.4.14; /** * Standard EIP-20 token with an interface marker. * * @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract. * */ contract StandardTokenExt is Recoverable, StandardToken { /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } } // File: contracts/ico/ReleasableToken.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ pragma solidity ^0.4.8; /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardTokenExt { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { if(!released) { if(!transferAgents[_sender]) { throw; } } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { if(releaseState != released) { throw; } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { throw; } _; } function transfer(address _to, uint _value) canTransfer(msg.sender) public returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) public returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } // File: contracts/WhitelistableToken.sol contract WhitelistableToken is ReleasableToken { /** * A pre-release list of investors */ struct WhitelistedInvestor { uint idx; bool whitelisted; } mapping(address => WhitelistedInvestor) whitelist; mapping(uint => address) indexedWhitelist; uint whitelistTotal; address public whitelistAgent; // Address responsible for adding investors to the whitelist. modifier isWhitelisted(address _destination) { if(!released) { if(!whitelist[_destination].whitelisted) { revert(); } } _; } modifier onlyWhitelistAgent(address _sender) { if(_sender != whitelistAgent) { revert(); } _; } function isOnWhitelist(address _investor) public view returns (bool whitelisted) { return whitelist[_investor].whitelisted; } function addToWhitelist(address _investor) public onlyWhitelistAgent(msg.sender) { if (!whitelist[_investor].whitelisted) { // Should be idempotent to keep duplicates out whitelist[_investor].whitelisted = true; whitelist[_investor].idx = whitelistTotal; indexedWhitelist[whitelistTotal] = _investor; whitelistTotal += 1; } } function removeFromWhitelist(address _investor) public onlyWhitelistAgent(msg.sender) { if (!whitelist[_investor].whitelisted) { revert(); } whitelist[_investor].whitelisted = false; uint idx = whitelist[_investor].idx; indexedWhitelist[idx] = address(0); } function setWhitelistAgent(address agent) public onlyOwner { whitelistAgent = agent; } /** * Used for iteration. */ function getWhitelistTotal() public view returns (uint total) { return whitelistTotal; } function getWhitelistAt(uint idx) public view returns (address investor) { return indexedWhitelist[idx]; } function transfer(address _to, uint _value) isWhitelisted(_to) public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) isWhitelisted(_from) isWhitelisted(_to) public returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/SDAToken.sol // See the example here: // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/examples/SimpleToken.sol contract SDAToken is WhitelistableToken { /** * For Releasable tokens, a "transfer agent" can be assigned who is allowed to * transfer tokens between users. This effectively functions as an investor whitelist. * */ string public constant name = "Safe Digital Advertising"; // solium-disable-line uppercase string public constant symbol = "SDA"; // solium-disable-line uppercase uint8 public constant decimals = 8; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 400000000 * (10 ** uint256(decimals)); function SDAToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
solium-disable-line uppercase
string public constant name = "Safe Digital Advertising";
7,282,860
[ 1, 18281, 5077, 17, 8394, 17, 1369, 18966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 533, 1071, 5381, 508, 273, 315, 9890, 11678, 7053, 4052, 1097, 13734, 14432, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xB7987958CA0105aF80fd9444549aA757b13d31F5/sources/src/zkbob/ZkBobPool.sol
* @dev Performs a forced withdrawal by irreversibly killing an account. Callable only by the operator, if set during latest call to the commitForcedExit. Account cannot be recovered after such forced exit. any remaining or newly sent funds would be lost forever. Accumulated account energy is forfeited. @param _nullifier transfer nullifier to be used for withdrawal. @param _operator operator address set during commitForcedExit. @param _to withdrawn funds receiver. @param _amount total account balance to withdraw. @param _exitStart exit window start timestamp, should match one calculated in commitForcedExit. @param _exitEnd exit window end timestamp, should match one calculated in commitForcedExit. @param _cancel cancel a previously submitted expired forced exit instead of executing it./
function executeForcedExit( uint256 _nullifier, address _operator, address _to, uint256 _amount, uint256 _exitStart, uint256 _exitEnd, bool _cancel ) external { require(nullifiers[_nullifier] == 0, "ZkBobPool: doublespend detected"); require( committedForcedExits[_nullifier] == _hashForcedExit(_operator, _to, _amount, _exitStart, _exitEnd), "ZkBobPool: invalid forced exit" ); if (_cancel) { require(block.timestamp >= _exitEnd, "ZkBobPool: exit not expired"); delete committedForcedExits[_nullifier]; emit CancelForcedExit(_nullifier); return; } require(_operator == address(0) || _operator == msg.sender, "ZkBobPool: invalid caller"); require(block.timestamp >= _exitStart && block.timestamp < _exitEnd, "ZkBobPool: exit not allowed"); (IZkBobAccounting acc, uint96 poolIndex) = (accounting, pool_index); if (address(acc) != address(0)) { acc.recordOperation(IZkBobAccounting.TxType.ForcedExit, address(0), int256(_amount)); } nullifiers[_nullifier] = poolIndex | uint256(0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead0000000000000000); IERC20(token).safeTransfer(_to, _amount * TOKEN_DENOMINATOR / TOKEN_NUMERATOR); emit ForcedExit(poolIndex, _nullifier, _to, _amount); }
1,854,160
[ 1, 9409, 279, 13852, 598, 9446, 287, 635, 9482, 266, 2496, 24755, 417, 5789, 392, 2236, 18, 10464, 1338, 635, 326, 3726, 16, 309, 444, 4982, 4891, 745, 358, 326, 3294, 1290, 3263, 6767, 18, 6590, 2780, 506, 24616, 1839, 4123, 13852, 2427, 18, 1281, 4463, 578, 10894, 3271, 284, 19156, 4102, 506, 13557, 21238, 18, 15980, 5283, 690, 2236, 12929, 353, 364, 3030, 16261, 18, 225, 389, 2011, 1251, 7412, 446, 1251, 358, 506, 1399, 364, 598, 9446, 287, 18, 225, 389, 9497, 3726, 1758, 444, 4982, 3294, 1290, 3263, 6767, 18, 225, 389, 869, 598, 9446, 82, 284, 19156, 5971, 18, 225, 389, 8949, 2078, 2236, 11013, 358, 598, 9446, 18, 225, 389, 8593, 1685, 2427, 2742, 787, 2858, 16, 1410, 845, 1245, 8894, 316, 3294, 1290, 3263, 6767, 18, 225, 389, 8593, 1638, 2427, 2742, 679, 2858, 16, 1410, 845, 1245, 8894, 316, 3294, 1290, 3263, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1836, 1290, 3263, 6767, 12, 203, 3639, 2254, 5034, 389, 2011, 1251, 16, 203, 3639, 1758, 389, 9497, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 8593, 1685, 16, 203, 3639, 2254, 5034, 389, 8593, 1638, 16, 203, 3639, 1426, 389, 10996, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 2011, 3383, 63, 67, 2011, 1251, 65, 422, 374, 16, 315, 62, 79, 38, 947, 2864, 30, 31446, 1302, 8316, 8863, 203, 3639, 2583, 12, 203, 5411, 16015, 1290, 3263, 424, 1282, 63, 67, 2011, 1251, 65, 422, 389, 2816, 1290, 3263, 6767, 24899, 9497, 16, 389, 869, 16, 389, 8949, 16, 389, 8593, 1685, 16, 389, 8593, 1638, 3631, 203, 5411, 315, 62, 79, 38, 947, 2864, 30, 2057, 13852, 2427, 6, 203, 3639, 11272, 203, 3639, 309, 261, 67, 10996, 13, 288, 203, 5411, 2583, 12, 2629, 18, 5508, 1545, 389, 8593, 1638, 16, 315, 62, 79, 38, 947, 2864, 30, 2427, 486, 7708, 8863, 203, 5411, 1430, 16015, 1290, 3263, 424, 1282, 63, 67, 2011, 1251, 15533, 203, 203, 5411, 3626, 10347, 1290, 3263, 6767, 24899, 2011, 1251, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2583, 24899, 9497, 422, 1758, 12, 20, 13, 747, 389, 9497, 422, 1234, 18, 15330, 16, 315, 62, 79, 38, 947, 2864, 30, 2057, 4894, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 389, 8593, 1685, 597, 1203, 18, 5508, 411, 389, 8593, 2 ]
./full_match/44787/0xfC9ca4F09d898244c4663Afa751852B38980452B/sources/contracts/StarFarm.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; SlotInfo memory slot; require(user.amount >= _amount, "withdraw: amount error"); updatePool(_pid,1); (slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender()); uint256 _amountGain = user.amount.add(user.amount.mul(slot._selfGain.add(slot._parentGain)).div(100)); uint256 accStarPerShare = pool.accStarPerShare; uint256 lpSupply = pool.lpSupply.add(pool.extraAmount); if (block.number > pool.lastRewardBlock && lpSupply != 0) { slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number); slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = slot.starReward.mul(1e12).div(lpSupply); } if(_amountGain >0){ slot._amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12); emit WithdrawTL(user.reward, slot._amountpendingStar); user.reward = user.reward.add(slot._amountpendingStar); } uint256 pending = user.reward; if(pending > 0) { iToken.farmMint(address(this), pending); starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(10000)); starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(10000)); pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(10000)); starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(10000)); pending = pending.sub(pending.mul(rewardRatio).div(10000)); pending = pending.div(slot._selfGain.add(slot._parentGain).add(100)).mul(100); if (user.lastDeposit > block.timestamp.sub(604800)) { slot.fee = pending.mul(pool.fee).div(10000); starToken.safeTransfer(_msgSender(), (pending.sub(slot.fee)).mul(slot._selfGain.add(100)).div(100)); starNode.settleNode(_msgSender(), (pending.sub(slot.fee)).mul(slot._parentGain).div(100)); user.rewardDebt = user.rewardDebt.add((pending.sub(slot.fee)).mul(slot._selfGain.add(100)).div(100)); if(pool.fee > 0){ starToken.safeTransfer(lockAddr, slot.fee.mul(Bonus.getlockRatio()).div(100)); starToken.safeTransfer(bonusAddr, slot.fee.mul(100 - Bonus.getlockRatio()).div(100)); uint256 indexLength = nftLogic.getAllTokenId().length; if(indexLength > 0){ uint256 divAmountBonus = slot.fee.mul(100 - Bonus.getlockRatio()).div(100).mul(1e12).div(indexLength); for(uint256 i = 0;i< indexLength;i++){ uint256 tokenId = nftLogic.getAllTokenId()[i]; uint256 UserBonusToken = nftLogic.disposeBonusToke(tokenId); nftLogic.setBonusToke(tokenId,divAmountBonus.div(1e12).add(UserBonusToken)); } } } starToken.safeTransfer(_msgSender(), pending); starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100)); user.rewardDebt = user.rewardDebt.add(pending); } user.reward = 0; pool.accStarPerShare = accStarPerShare; } if(_amount > 0) { user.amount = user.amount.sub(_amount); uint256 _extraAmount = _amount.mul(slot._selfGain.add(slot._parentGain)).div(100); pool.extraAmount = pool.extraAmount.sub(_extraAmount); pool.lpSupply = pool.lpSupply.sub(_amount); pool.lpToken.safeTransfer(_msgSender(), _amount); } emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]); }
13,276,501
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 3576, 12021, 1435, 15533, 203, 3639, 23195, 966, 3778, 4694, 31, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 3844, 555, 8863, 203, 3639, 1089, 2864, 24899, 6610, 16, 21, 1769, 203, 203, 3639, 261, 14194, 6315, 2890, 43, 530, 16, 4694, 6315, 2938, 43, 530, 13, 273, 10443, 907, 18, 2159, 43, 530, 24899, 3576, 12021, 10663, 203, 3639, 2254, 5034, 389, 8949, 43, 530, 273, 729, 18, 8949, 18, 1289, 12, 1355, 18, 8949, 18, 16411, 12, 14194, 6315, 2890, 43, 530, 18, 1289, 12, 14194, 6315, 2938, 43, 530, 13, 2934, 2892, 12, 6625, 10019, 203, 3639, 2254, 5034, 4078, 18379, 2173, 9535, 273, 2845, 18, 8981, 18379, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 3088, 1283, 18, 1289, 12, 6011, 18, 7763, 6275, 1769, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 4694, 18, 20538, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 4694, 18, 10983, 17631, 1060, 273, 4694, 18, 20538, 18, 16411, 12, 10983, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 2 ]
pragma solidity ^0.4.25; contract FOMOEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 tokenAmount, uint256 genAmount, uint256 potAmount, uint256 seedAdd ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 tokenAmount, uint256 genAmount, uint256 seedAdd ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 tokenAmount, uint256 genAmount, uint256 seedAdd ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 tokenAmount, uint256 genAmount, uint256 seedAdd ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract FFEIF is FOMOEvents { using SafeMath for *; using NameFilter for string; PlayerBookInterface private PlayerBook; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== PoEIF public PoEIFContract; address private admin = msg.sender; string constant public name = "Fomo Forever EIF"; string constant public symbol = "FFEIF"; uint256 private rndExtra_ = 1 minutes; // length of the very first ICO uint256 public rndGap_ = 1 minutes; // length of ICO phase, set to 1 year for EOS. uint256 public rndInit_ = 60 minutes; // round timer starts at this uint256 public rndInc_ = 1 seconds; // every full FFEIF purchased adds this much to the timer uint256 public rndIncDivisor_ = 1; // divides the above by this amount (useful for less than 1 second per FFEIF when setting shorter rounds) uint256 public potSeedRate = 100; // pot increase per hour from seedingPot (divided into seedingPot) - default 100 means 1% per hour is added uint256 public potNextSeedTime = 0; // time for the next increase (increases by an hour each time it is processed) uint256 public seedingPot = 0; // this keeps track of the amount left to feed the pot - initially has nothing but can be fed by anyone uint256 public seedingThreshold = 0 ether; // for the first x ETH (or however it is set) of each round, all pot increases go to the seeding rather than the actual pot uint256 public seedingDivisor = 2; // after the threshold, the pot amount is divided by this and added to the seedingPot i.e. half - a higher divisor means less goes into seeding uint256 public seedRoundEnd = 1; // if nextRoundPercentage will also add to seeding pot as normal or instead fully goes to the pot uint256 public linearPrice = 75000000000000; // if non-zero will set a fixed price - otherwise normal fomo scaling which is fairly linear still uint256 public multPurchase = 0; // number of FFEIF needed to purchase for the multiplier to go up.... 0 means it has to be a qualifying purchase of the multiplier amount of FFEIF i.e. enough to make the user the winner if nobody else buys enough afterwards... uint256 public multAllowLast = 1; // Whether the current winner (last qualifying purchaser) can increase the multiplier - this could be used as a tactic to win uint256 public multLinear = 2; // multiplier increases linearly, if not the multiplier is multiplied rather than added to each time a sufficient amount is purchased // NOTE: If the value is 2 then it is linear until multStart is reached..... uint256 public maxMult = 1000000; // The maximum value of multiplier (remember it is 10 times the real value); uint256 public multInc_ = 0; // every purchase (any amount greater than multPurchase) adds this much to the multiplier but divided by 10 - a value of 10 means a real increase of 1 per purchase // NOTE: For non-linear increases, this real value is added to 1 and multiplied - i.e. 10 would mean it doubles each time // NOTE2: If multInc_ is 0, the amount of FFEIF purchased is used as the value (which is still ten times more than the real value) uint256 public multIncFactor_ = 10; // Further factor to multiply multInc_ by before processing (this is for finer adjustments when multInc_ is set to 0) uint256 public multLastChange = now; // stores timestamp of the last increase/decrease so the next decay can by calculated - note that for non-linear decay, the timestamp only changes to the next minute or multiple of minutes that have passed uint256 public multDecayPerMinute = 1; // every minute the multiplier reduces by this amount (isn't X10 this time so is the true decrease per minute - i.e. 1) // NOTE: For non-linear decay, a value of 1 means it halves every minute (1 is added to the amount and divided rather than subtracted) uint256 public multStart = 24 hours; // the max time that should be left for the multiplier to increase through more purchases - won't increase when timer is above this uint256 public multCurrent = 10; // the current multiplier times 10 - defaults to a real value of 1 and this is also the minimum allowed uint256 public rndMax_ = 24 hours; // max length a round timer can be uint256 public earlyRoundLimit = 1e18; // limit of 1ETH per player (not per purchase) until earlyRoundLimitUntil uint256 public earlyRoundLimitUntil = 100e18; // when limiter ends uint256 public divPercentage = 65; // max 75% and can be configured - potPercentage is implied from the rest - 5% each for PoEIF and EIF is fixed uint256 public affFee = 5; // aff fee default is 5% and max is 15% uint256 public potPercentage = 20; // 90 - divPercentage - affFee (seeding divisor applies to this) uint256 public divPotPercentage = 15; // max 50% and can be configured - winnerPercentage is implied from the rest - 5% each for PoEIF and EIF is fixed uint256 public nextRoundPercentage = 25; // max 40% and is the amount carried to the next round (since it is going to the pot, the seeding divisor ratio also applies to this if seedRoundEnd is 1) uint256 public winnerPercentage = 50; // 90 - divPotPercentage - nextRoundPercentatge uint256 public fundEIF = 0; // the EasyInvestForever accumulated fund yet to be sent (5% of incoming ETH) uint256 public totalEIF = 0; // total EasyInvestForever fund already sent uint256 public seedDonated = 0; // total sent to seedingPot payable function (doesn't keep track of msg.sender) address public FundEIF = 0x0111E8A755a4212E6E1f13e75b1EABa8f837a213; // Usual fund address to send EIF funds too - updateable //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => FFEIFDatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => FFEIFDatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => FFEIFDatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => FFEIFDatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => FFEIFDatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { PoEIFContract = PoEIF(0xFfB8ccA6D55762dF595F21E78f21CD8DfeadF1C8); PlayerBook = PlayerBookInterface(0xd80e96496cd0B3F95bB4941b1385023fBCa1E6Ba); } //============================================================================== // _ _ _ _ . // | |(/_|/\| . (these are for multiplier and new functions) //============================================================================== function updateFundAddress(address _newAddress) onlyAdmin() public { FundEIF = _newAddress; } /** * @dev calculates number of FFEIF received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal view returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X FFEIF * @param _curKeys current amount of FFEIF that exist * @param _sellKeys amount of FFEIF you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal view returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many FFEIF would exist with given an amount of eth * @param _eth eth "in contract" * @return number of FFEIF that would exist */ function keys(uint256 _eth) internal view returns(uint256) { if (linearPrice==0) {return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);} else {return 1e18.mul(_eth) / linearPrice;} } /** * @dev calculates how much eth would be in contract given a number of FFEIF * @param _keys number of FFEIF "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal view returns(uint256) { if (linearPrice==0) {return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());} else {return _keys.mul(linearPrice)/1e18;} } function payFund() public { //Registration fee goes to EIF - function must be called manually so enough gas is sent if(!FundEIF.call.value(fundEIF)()) { revert(); } totalEIF = totalEIF.add(fundEIF); fundEIF = 0; } function calcMult(uint256 keysBought, bool validIncrease) internal returns (bool) { uint256 _now = now; //make local variable uint256 secondsPassed = _now - multLastChange; //stores boolean for whether time left has reached the threshold for multiplier to be active - may still be active in special case bool thresholdReached = (multStart > round_[rID_].end - _now); // work out if linear and update the last change time depending on this // multLastChange updates all the time even when multiplier inactive or at minimum and doesn't change bool currentlyLinear = false; if (multLinear == 1 || (multLinear == 2 && !thresholdReached)) { currentlyLinear = true; multLastChange = _now;} else multLastChange = multLastChange.add((secondsPassed/60).mul(60)); //updates every 60 seconds only // includes special case is where it changes from linear to non-linear when multLinear is set to 2 and thresholdReached //first apply the decay even when not active if (multCurrent >= 10) { if (currentlyLinear) multCurrent = (multCurrent.mul(10).sub(multDecayPerMinute.mul(secondsPassed).mul(100)/60))/10; else multCurrent = multCurrent / (1+(multDecayPerMinute.mul(secondsPassed)/60)); if (multCurrent < 10) multCurrent = 10; } // returnValue true if enough bought to be new winner - note that it is set before the increase but after the decay bool returnValue = ((keysBought / 1e17) >= multCurrent); // now increase the multiplier if active if ((thresholdReached || multLinear == 2) && validIncrease) { uint256 wholeKeysBought = keysBought / 1e18; uint256 actualMultInc = multIncFactor_.mul(wholeKeysBought); if (multInc_ != 0) actualMultInc = multInc_; // have enough FFEIF/keys been bought to increase multiplier if ((wholeKeysBought >= multPurchase && multPurchase > 0) || ((wholeKeysBought >= (multCurrent / 10)) && multPurchase == 0) ) { //now apply increase if (currentlyLinear) multCurrent = multCurrent.add(actualMultInc); else multCurrent = multCurrent.mul((1+(actualMultInc/10))); if (multCurrent > maxMult) multCurrent = maxMult; } } return returnValue; } function viewMult() public view returns (uint256) // since multiplier only increases when keys are bought, this will only estimate the decay { uint256 _now = now; //make local variable uint256 secondsPassed = _now - multLastChange; //stores boolean for whether time left has reached the threshold for multiplier to be active - may still be active in special case bool thresholdReached = (multStart > round_[rID_].end - _now); // work out if linear bool currentlyLinear = false; if (multLinear == 1 || (multLinear == 2 && !thresholdReached)) currentlyLinear = true; // includes special case is where it changes from linear to non-linear when multLinear is set to 2 and thresholdReached //first apply the decay even when not active uint256 _multCurrent = multCurrent; //create local if (_multCurrent >= 10) { if (currentlyLinear) _multCurrent = (_multCurrent.mul(10).sub(multDecayPerMinute.mul(secondsPassed).mul(100)/60))/10; else { //make approximation for display reasons uint256 proportion = secondsPassed % 60; _multCurrent = _multCurrent / (1+(multDecayPerMinute.mul(secondsPassed)/60)); uint256 _multCurrent2 = multCurrent / (1+(multDecayPerMinute.mul(secondsPassed+60)/60)); _multCurrent = _multCurrent - proportion.mul(_multCurrent - _multCurrent2)/60; } } if (_multCurrent < 10) _multCurrent = 10; return _multCurrent; } function viewPot() public view returns (uint256) // shows pot in realtime including proportion of seeding pot (so it rises every second) { uint256 _now = now; uint256 _pot = round_[rID_].pot; uint256 _seedingPot = seedingPot; uint256 _potSeedRate = potSeedRate; uint256 _potNextSeedTime = potNextSeedTime; // emulate seeding to also make sure potNextSeedTime is not before _now while (_potNextSeedTime<now) {_pot = _pot.add(_seedingPot/_potSeedRate); _seedingPot = _seedingPot.sub(_seedingPot/_potSeedRate); _potNextSeedTime += 3600;} //time left for hourly real update uint256 timeLeft = potNextSeedTime - _now; // return calculated estimate - the usually negligible sub-hour extra is not actually won at round end (waste of gas to implement) but is for display reasons return ((3600-timeLeft).mul(_seedingPot/_potSeedRate)/3600 ).add(_pot); } uint numElements = 0; uint256[] varvalue; string[] varname; function insert(string _var, uint256 _value) internal { if(numElements == varvalue.length) { varvalue.length ++; varname.length ++; } varvalue[numElements] = _value; varname[numElements] = _var; numElements++; } function setStore(string _variable, uint256 _value) public { // we used uint256 for everything here // add any new configuration change to array list - admin only and ignore the dummy values sent by endround function if (keccak256(bytes(_variable))!=keccak256("endround") && msg.sender == admin) insert(_variable,_value); // if round has ended, update all variables and reset array index afterwards to effectively clear it if (round_[rID_].ended || activated_ == false) { //now loop through all elements for (uint i=0; i<numElements; i++) { bytes32 _varname = keccak256(bytes(varname[i])); if (_varname==keccak256('rndGap_')) rndGap_=varvalue[i]; else if (_varname==keccak256('rndInit_')) rndInit_=varvalue[i]; else if (_varname==keccak256('rndInc_')) rndInc_=varvalue[i]; else if (_varname==keccak256('rndIncDivisor_')) rndIncDivisor_=varvalue[i]; else if (_varname==keccak256('potSeedRate')) potSeedRate=varvalue[i]; else if (_varname==keccak256('potNextSeedTime')) potNextSeedTime=varvalue[i]; else if (_varname==keccak256('seedingThreshold')) seedingThreshold=varvalue[i]; else if (_varname==keccak256('seedingDivisor')) seedingDivisor=varvalue[i]; else if (_varname==keccak256('seedRoundEnd')) seedRoundEnd=varvalue[i]; else if (_varname==keccak256('linearPrice')) linearPrice=varvalue[i]; else if (_varname==keccak256('multPurchase')) multPurchase=varvalue[i]; else if (_varname==keccak256('multAllowLast')) multAllowLast=varvalue[i]; else if (_varname==keccak256('maxMult')) maxMult=varvalue[i]; else if (_varname==keccak256('multInc_')) multInc_=varvalue[i]; else if (_varname==keccak256('multIncFactor_')) multIncFactor_=varvalue[i]; else if (_varname==keccak256('multLastChange')) multLastChange=varvalue[i]; else if (_varname==keccak256('multDecayPerMinute')) multDecayPerMinute=varvalue[i]; else if (_varname==keccak256('multStart')) multStart=varvalue[i]; else if (_varname==keccak256('multCurrent')) multCurrent=varvalue[i]; else if (_varname==keccak256('rndMax_')) rndMax_=varvalue[i]; else if (_varname==keccak256('earlyRoundLimit')) earlyRoundLimit=varvalue[i]; else if (_varname==keccak256('earlyRoundLimitUntil')) earlyRoundLimitUntil=varvalue[i]; else if (_varname==keccak256('divPercentage')) {divPercentage=varvalue[i]; if (divPercentage>75) divPercentage=75;} else if (_varname==keccak256('divPotPercentage')) {divPotPercentage=varvalue[i]; if (divPotPercentage>50) divPotPercentage=50;} else if (_varname==keccak256('nextRoundPercentage')) {nextRoundPercentage=varvalue[i]; if (nextRoundPercentage>40) nextRoundPercentage=40;} else if (_varname==keccak256('affFee')) {affFee=varvalue[i]; if (affFee>15) affFee=15;} } //clear elements by resetting index numElements = 0; // recalculate pot and winner percentages - assume SafeMath not needed due to max values being enforced winnerPercentage = 90 - divPotPercentage - nextRoundPercentage; potPercentage = 90 - divPercentage - affFee; // reset multiplier to minimum multCurrent = 10; // finally update legacy arrays fees_[0] = FFEIFDatasets.TeamFee(divPercentage,10); // rest to aff (affFee) and potPercentage potSplit_[0] = FFEIFDatasets.PotSplit(divPotPercentage,10); // also winnerPercentage to winner, nextRoundPercentage to next round } } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true); // quick one-line hack to feed pot from seedingPot - adds one hour each time so may loop a few times if contract has been dormant while (potNextSeedTime<now) {round_[rID_].pot = round_[rID_].pot.add(seedingPot/potSeedRate); seedingPot = seedingPot.sub(seedingPot/potSeedRate); potNextSeedTime += 3600; } _; } /** * @dev prevents other contracts from interacting with this one */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require (msg.sender == tx.origin); assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000); require(_eth <= 100000000000000000000000); _; } modifier onlyAdmin() { require(msg.sender == admin); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FFEIFDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } function seedDeposit() isWithinLimits(msg.value) public payable { // add to seedingPot seedingPot = seedingPot.add(msg.value); seedDonated = seedDonated.add(msg.value); } /** * @dev converts all incoming ethereum to FFEIF. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FFEIFDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FFEIFDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FFEIFDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FFEIFDatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FFEIFDatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FFEIFDatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run endround yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data FFEIFDatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit FOMOEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.tokenAmount, _eventData_.genAmount, _eventData_.seedAdd ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit FOMOEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FOMOEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FOMOEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FOMOEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual FFEIF. * -functionhash- 0x018a25e8 * @return price for next FFEIF bought (in wei format) */ function getBuyPrice() public view returns(uint256) { //starting key/FFEIF price uint256 _startingPrice = 75000000000000; if (linearPrice != 0) _startingPrice = linearPrice; // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( ethRec((round_[_rID].keys.add(1000000000000000000)),1000000000000000000) ); else // rounds over. need price for new round return ( _startingPrice ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but endround has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(winnerPercentage)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and endround has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total FFEIF for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return team eth in for round */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0] //9 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return FFEIF owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr = msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, FFEIFDatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, 0, _eventData_); // if round is not active } else { // check to see if endround needs to be run if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FOMOEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.tokenAmount, _eventData_.genAmount, _eventData_.seedAdd ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, FFEIFDatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, 0, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FOMOEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.tokenAmount, _eventData_.genAmount, _eventData_.seedAdd ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, FFEIFDatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < earlyRoundLimitUntil && plyrRnds_[_pID][_rID].eth.add(_eth) > earlyRoundLimit) { uint256 _availableLimit = (earlyRoundLimit).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // above minimum amount for normal buys if (_eth > 1000000000) { // mint the new FFEIF uint256 _keys = keysRec(round_[_rID].eth,_eth); // calculate the new multiplier and returns true if new winner (they bought enough) bool newWinner = calcMult(_keys, multAllowLast==1 || round_[_rID].plyr != _pID); // if they bought at least 1 whole FFEIF if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); if (newWinner) { // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][0] = _eth.add(rndTmEth_[_rID][0]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 0, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, 0, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, 0, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of FFEIF you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return keysRec(round_[_rID].eth,_eth); else // rounds over. need FFEIF for new round return keys(_eth); } /** * @dev returns current eth price for X FFEIF. * -functionhash- 0xcf808000 * @param _keys number of FFEIF desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ethRec(round_[_rID].keys.add(_keys),_keys); else // rounds over. need price for new round return eth(_keys); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook)); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook)); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(FFEIFDatasets.EventReturns memory _eventData_) private returns (FFEIFDatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, FFEIFDatasets.EventReturns memory _eventData_) private returns (FFEIFDatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(FFEIFDatasets.EventReturns memory _eventData_) private returns (FFEIFDatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // tokenholder share, and amount reserved for next pot uint256 _win = _pot.mul(winnerPercentage) / 100; // to winner uint256 _gen = _pot.mul(potSplit_[_winTID].gen) / 100; // divs to FFEIF buyers uint256 _PoEIF = _pot.mul(potSplit_[_winTID].poeif) / 100; // to PoEIF/EIF smart contracts uint256 _res = _pot.sub(_win).sub(_gen).sub(_PoEIF); // amount for next round // calculate ppt for round mask uint256 _ppt = _gen.mul(1000000000000000000) / round_[_rID].keys; uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // send ETH to PoEIF holders and to EIF contract (50% each) address(PoEIFContract).call.value(_PoEIF.sub((_PoEIF / 2)))(bytes4(keccak256("donateDivs()"))); fundEIF = fundEIF.add(_PoEIF / 2); // distribute gen portion to FFEIF holders round_[_rID].mask = _ppt.add(round_[_rID].mask); uint256 _actualPot = _res; // send appropriate portion of _res to seeding pot if (seedRoundEnd==1) { // stick half into seedingPot and the remainder is the amount actually added to pot - seedingDivisor default is 2 which means half goes into seedingPot _actualPot = _res.sub(_res/seedingDivisor); // if seedingThreshold exceeds eth in the round then put all into seeding pot, else just half if (seedingThreshold > rndTmEth_[_rID][0]) {seedingPot = seedingPot.add(_res); _actualPot = 0;} else seedingPot = seedingPot.add(_res/seedingDivisor); } // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.tokenAmount = _PoEIF; _eventData_.newPot = _actualPot; _eventData_.seedAdd = _res - _actualPot; // start next round setStore("endround",0); // update any config changes rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot += _actualPot; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole FFEIF bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of FFEIF bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)/rndIncDivisor_).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)/rndIncDivisor_).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to aff and PoEIF */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, FFEIFDatasets.EventReturns memory _eventData_) private returns(FFEIFDatasets.EventReturns) { uint256 _PoEIF; // distribute share to affiliate (default 5%) uint256 _aff = _eth.mul(affFee) / 100; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit FOMOEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _PoEIF = _aff; } // pay out poeif _PoEIF = _PoEIF.add((_eth.mul(fees_[_team].poeif)) / 100); if (_PoEIF > 0) { // deposit to divies contract uint256 _EIFamount = _PoEIF / 2; address(PoEIFContract).call.value(_PoEIF.sub(_EIFamount))(bytes4(keccak256("donateDivs()"))); fundEIF = fundEIF.add(_EIFamount); // set up event data _eventData_.tokenAmount = _PoEIF.add(_eventData_.tokenAmount); } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, FFEIFDatasets.EventReturns memory _eventData_) private returns(FFEIFDatasets.EventReturns) { // calculate gen share uint256 _gen = _eth.mul(fees_[_team].gen) / 100; // update eth balance (eth = eth - (aff share + poeif share)) _eth = _eth.sub(((_eth.mul(affFee)) / 100).add((_eth.mul(fees_[_team].poeif)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // stick half into seedingPot and the remainder is the amount actually added to pot - seedingDivisor default is 2 which means half goes into seedingPot uint256 _actualPot = _pot.sub(_pot/seedingDivisor); // if seedingThreshold exceeds eth in the round then put all into seeding pot, else just half if (seedingThreshold > rndTmEth_[_rID][0]) {seedingPot = seedingPot.add(_pot); _actualPot = 0;} else seedingPot = seedingPot.add(_pot/seedingDivisor); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _actualPot.add(_dust).add(round_[_rID].pot); // set up event data - pot amount excludes seeding _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _actualPot; _eventData_.seedAdd = _pot - _actualPot; return(_eventData_); } /** * @dev updates masks for round and player when FFEIF are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per FFEIF & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the FFEIF // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, FFEIFDatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit FOMOEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.tokenAmount, _eventData_.genAmount, _eventData_.potAmount, _eventData_.seedAdd ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin, "Only admin can activate"); // can only be ran once require(activated_ == false, "FFEIF already activated"); // update any configuration changes setStore("endround",0); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; //set potNextSeedTime to current block timestamp plus one hour potNextSeedTime = now + 3600; } function removeAdmin() //stops any further updates happening to make it completely autonomous public { require(msg.sender == admin, "Only admin can remove himself"); admin = address(0); // dummy 0x000... address } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library FFEIFDatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 tokenAmount; // amount distributed to PoEIF tokenholders and EIF uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot uint256 seedAdd; // amount added to seedingPot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // FFEIF/keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // FFEIF/keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average FFEIF price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to FFEIF holders of current round uint256 poeif; // % of buy in thats paid to PoEIF holders and EIF } struct PotSplit { uint256 gen; // % of pot thats paid to FFEIF holders of current round uint256 poeif; // % of pot thats paid to PoEIF holders and EIF } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== //Define the PoEIF token for the sending 5% divs contract PoEIF { function donateDivs() public payable; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78); require(_temp[1] != 0x58); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a)); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
* @dev decides if round end needs to be run & new round started. and if player unmasked earnings from previously played rounds need to be moved./ if player has played a previous round, move their unmasked earnings from that round to gen vault. update player's last round played set the joined round bool to true
{ if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); }
12,594,927
[ 1, 4924, 4369, 309, 3643, 679, 4260, 358, 506, 1086, 473, 394, 3643, 5746, 18, 225, 471, 309, 7291, 640, 23455, 425, 1303, 899, 628, 7243, 6599, 329, 21196, 1608, 358, 506, 10456, 18, 19, 309, 7291, 711, 6599, 329, 279, 2416, 3643, 16, 3635, 3675, 640, 23455, 425, 1303, 899, 628, 716, 3643, 358, 3157, 9229, 18, 1089, 7291, 1807, 1142, 3643, 6599, 329, 444, 326, 12114, 3643, 1426, 358, 638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 309, 261, 1283, 86, 67, 63, 67, 84, 734, 8009, 10826, 4880, 480, 374, 13, 203, 5411, 1089, 7642, 12003, 24899, 84, 734, 16, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 10826, 4880, 1769, 203, 203, 3639, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 10826, 4880, 273, 436, 734, 67, 31, 203, 203, 3639, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 1728, 31, 203, 203, 3639, 327, 24899, 2575, 751, 67, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** * EtherDice - fully transparent and decentralized betting * * Web - https://etherdice.biz * Telegram chat - https://t.me/EtherDice * Telegram channel - https://t.me/EtherDiceInfo * * Recommended gas limit: 200000 * Recommended gas price: https://ethgasstation.info/ */ contract EtherDice { address public constant OWNER = 0x8026F25c6f898b4afE03d05F87e6c2AFeaaC3a3D; address public constant MANAGER = 0xD25BD6c44D6cF3C0358AB30ed5E89F2090409a79; uint constant public FEE_PERCENT = 2; uint public minBet; uint public maxBet; uint public currentIndex; uint public lockBalance; uint public betsOfBlock; uint entropy; struct Bet { address player; uint deposit; uint block; } Bet[] public bets; event PlaceBet(uint num, address player, uint bet, uint payout, uint roll, uint time); // Modifier on methods invokable only by contract owner and manager modifier onlyOwner { require(OWNER == msg.sender || MANAGER == msg.sender); _; } // This function called every time anyone sends a transaction to this contract function() public payable { if (msg.value > 0) { createBet(msg.sender, msg.value); } placeBets(); } // Records a new bet to the public storage function createBet(address _player, uint _deposit) internal { require(_deposit >= minBet && _deposit <= maxBet); // check deposit limits uint lastBlock = bets.length > 0 ? bets[bets.length-1].block : 0; require(block.number != lastBlock || betsOfBlock < 50); // maximum 50 bets per block uint fee = _deposit * FEE_PERCENT / 100; uint betAmount = _deposit - fee; require(betAmount * 2 + fee <= address(this).balance - lockBalance); // profit check sendOwner(fee); betsOfBlock = block.number != lastBlock ? 1 : betsOfBlock + 1; lockBalance += betAmount * 2; bets.push(Bet(_player, _deposit, block.number)); } // process all the bets of previous players function placeBets() internal { for (uint i = currentIndex; i < bets.length; i++) { Bet memory bet = bets[i]; if (bet.block < block.number) { uint betAmount = bet.deposit - bet.deposit * FEE_PERCENT / 100; lockBalance -= betAmount * 2; // Bets made more than 256 blocks ago are considered failed - this has to do // with EVM limitations on block hashes that are queryable if (block.number - bet.block <= 256) { entropy = uint(keccak256(abi.encodePacked(blockhash(bet.block), entropy))); uint roll = entropy % 100 + 1; uint payout = roll < 50 ? betAmount * 2 : 0; send(bet.player, payout); emit PlaceBet(i + 1, bet.player, bet.deposit, payout, roll, now); } } else { break; } } currentIndex = i; } // Safely sends the ETH by the passed parameters function send(address _receiver, uint _amount) internal { if (_amount > 0 && _receiver != address(0)) { _receiver.send(_amount); } } // Sends funds to the owner and manager function sendOwner(uint _amount) internal { send(OWNER, _amount * 7 / 10); send(MANAGER, _amount * 3 / 10); } // Funds withdrawal function withdraw(uint _amount) public onlyOwner { require(_amount <= address(this).balance - lockBalance); sendOwner(_amount); } // Set limits for deposits function configure(uint _minBet, uint _maxBet) onlyOwner public { require(_minBet >= 0.001 ether && _minBet <= _maxBet); minBet = _minBet; maxBet = _maxBet; } // This function deliberately left empty. It's primary use case is to top up the bank roll function deposit() public payable {} // Returns the number of bets created function totalBets() public view returns(uint) { return bets.length; } }
Records a new bet to the public storage
function createBet(address _player, uint _deposit) internal { uint lastBlock = bets.length > 0 ? bets[bets.length-1].block : 0; uint fee = _deposit * FEE_PERCENT / 100; uint betAmount = _deposit - fee; sendOwner(fee); betsOfBlock = block.number != lastBlock ? 1 : betsOfBlock + 1; lockBalance += betAmount * 2; bets.push(Bet(_player, _deposit, block.number)); }
12,988,732
[ 1, 6499, 279, 394, 2701, 358, 326, 1071, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 38, 278, 12, 2867, 389, 14872, 16, 2254, 389, 323, 1724, 13, 2713, 288, 203, 540, 203, 540, 203, 3639, 2254, 1142, 1768, 273, 324, 2413, 18, 2469, 405, 374, 692, 324, 2413, 63, 70, 2413, 18, 2469, 17, 21, 8009, 2629, 294, 374, 31, 203, 540, 203, 540, 203, 3639, 2254, 14036, 273, 389, 323, 1724, 380, 478, 9383, 67, 3194, 19666, 342, 2130, 31, 203, 3639, 2254, 2701, 6275, 273, 389, 323, 1724, 300, 14036, 31, 7010, 540, 203, 540, 203, 3639, 1366, 5541, 12, 21386, 1769, 203, 540, 203, 3639, 324, 2413, 951, 1768, 273, 1203, 18, 2696, 480, 1142, 1768, 692, 404, 294, 324, 2413, 951, 1768, 397, 404, 31, 203, 3639, 2176, 13937, 1011, 2701, 6275, 380, 576, 31, 203, 3639, 324, 2413, 18, 6206, 12, 38, 278, 24899, 14872, 16, 389, 323, 1724, 16, 1203, 18, 2696, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7DF18E4eFD6e6f73cfb462937dAC40FE42533016/sources/contracts/ZkittyToken.sol
when buywhen sellwhen transfer if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
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"); require(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTradingAmount[to] ) { require( amount <= maxTradingAmount, "Buy transfer amount exceeds the maxTradingAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTradingAmount[from] ) { require( amount <= maxTradingAmount, "Sell transfer amount exceeds the maxTradingAmount." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(FEE_BASE); tokensForLiquidity += (fees * liquidityFee) / FEE_BASE; tokensForTeam += (fees * teamFee) / FEE_BASE; tokensForRevShare += (fees * revShareFee) / FEE_BASE; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(FEE_BASE); tokensForLiquidity += (fees * liquidityFee) / FEE_BASE; tokensForTeam += (fees * teamFee) / FEE_BASE; tokensForRevShare += (fees * revShareFee) / FEE_BASE; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
4,888,121
[ 1, 13723, 30143, 13723, 357, 80, 13723, 7412, 309, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 2080, 6487, 315, 12021, 25350, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 869, 6487, 315, 12952, 25350, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 7734, 309, 261, 203, 10792, 18472, 690, 3882, 278, 12373, 10409, 63, 2080, 65, 597, 203, 10792, 401, 67, 291, 16461, 2 ]
pragma solidity ^0.4.25; contract EthCrystal { /* EthCrystal.com Thanks for choosing us! ███████╗████████╗██╗ ██╗ ██████╗██████╗ ██╗ ██╗███████╗████████╗ █████╗ ██╗ ██████╗ ██████╗ ███╗ ███╗ ██╔════╝╚══██╔══╝██║ ██║██╔════╝██╔══██╗╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔══██╗██║ ██╔════╝██╔═══██╗████╗ ████║ █████╗ ██║ ███████║██║ ██████╔╝ ╚████╔╝ ███████╗ ██║ ███████║██║ ██║ ██║ ██║██╔████╔██║ ██╔══╝ ██║ ██╔══██║██║ ██╔══██╗ ╚██╔╝ ╚════██║ ██║ ██╔══██║██║ ██║ ██║ ██║██║╚██╔╝██║ ███████╗ ██║ ██║ ██║╚██████╗██║ ██║ ██║ ███████║ ██║ ██║ ██║███████╗██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ####### ##### # ##### # # # # ##### # # #### ##### ## # #### #### # # # # # # # # # # # # # # # # # # # # ## ## ##### # ###### # # # # #### # # # # # # # # ## # # # # # # ##### # # # ###### # ### # # # # # # # # # # # # # # # # # # # # ### # # # # # # ####### # # # ##### # # # #### # # # ###### ### #### #### # # Telegram: t.me/EthCrystalGame This is the second versoin of our smart-contract. We have fixed all bugs and set the new speed values for Rounds so it is easier for users to play. The first smart-contract address is: 0x5c6d8bb345f4299c76f24fc771ef04dd160c4d36 There is no code which can be only executed by the contract creators. */ using SafeMath for *; // Tower Type details struct TowersInfoList { string name; // Tower name uint256 timeLimit; // Maximum time increasement uint256 warriorToTime; // Amount of seconds each warrior adds uint256 currentRoundID; // Current Round ID uint256 growthCoefficient; // Each warrior being bought increases the price of the next warrior. uint256 winnerShare; // % to winner after the round [Active Fond] uint256 nextRound; // % to next round pot uint256 dividendShare; // % as dividends to holders after the round mapping (uint256 => TowersInfo) RoundList; // Here the Rounds for each Tower are stored } // Round details struct TowersInfo { uint256 roundID; // The Current Round ID uint256 towerBalance; // Balance for distribution in the end uint256 totalBalance; // Total balance with referrer or dev % uint256 totalWarriors; // Total warriors being bought uint256 timeToFinish; // The time when the round will be finished uint256 timeLimit; // The maximum increasement uint256 warriorToTime; // Amount of seconds each warrior adds uint256 bonusPot; // % of tower balance from the previous round address lastPlayer; // The last player bought warriors } // Player Details struct PlayerInfo { uint256 playerID; // Player's Unique Identifier address playerAddress; // Player's Ethereum Address address referralAddress; // Store the Ethereum Address of the referrer string nickname; // Player's Nickname mapping (uint256 => TowersRoundInfo) TowersList; } struct TowersRoundInfo { uint256 _TowerType; mapping (uint256 => PlayerRoundInfo) RoundList; } // All player's warriors for a particular Round struct PlayerRoundInfo { uint256 warriors; uint256 cashedOut; // To Allow cashing out before the game finished } // In-Game balance (Returnings + Referral Payings) struct ReferralInfo { uint256 balance; } uint256 public playerID_counter = 1; // The Unique Identifier for the next created player uint256 public devShare = 5; // % to devs uint256 public affShare = 10; // bounty % to reffers mapping (address => PlayerInfo) public players; // Storage for players mapping (uint256 => PlayerInfo) public playersByID; // Duplicate of the storage for players mapping (address => ReferralInfo) public aff; // Storage for player refferal and returnings balances. mapping (uint256 => TowersInfoList) public GameRounds; // Storage for Tower Rounds address public ownerAddress; // The address of the contract creator event BuyEvent(address player, uint256 TowerID, uint256 RoundID, uint256 TotalWarriors, uint256 WarriorPrice, uint256 TimeLeft); constructor() public { ownerAddress = msg.sender; // Setting the address of the contact creator // Creating Tower Types GameRounds[0] = TowersInfoList("Crystal Tower", 60*60*3, 60*3, 0, 10000000000000, 35, 15, 50); GameRounds[1] = TowersInfoList("Red Tower", 60*60*3, 60*3, 0, 20000000000000, 25, 5, 70); GameRounds[2] = TowersInfoList("Gold Tower", 60*60*3, 60*3, 0, 250000000000000, 40, 10, 50); GameRounds[3] = TowersInfoList("Purple Tower", 60*60*6, 60*3, 0, 5000000000000000, 30, 10, 60); GameRounds[4] = TowersInfoList("Silver Tower", 60*60*6, 60*3, 0, 1000000000000000, 35, 15, 50); GameRounds[5] = TowersInfoList("Black Tower", 60*60*6, 60*3, 0, 1000000000000000, 65, 10, 25); GameRounds[6] = TowersInfoList("Toxic Tower", 60*60*6, 60*3, 0, 2000000000000000, 65, 10, 25); // Creating first Rounds for each Tower Type newRound(0); newRound(1); newRound(2); newRound(3); newRound(4); newRound(5); newRound(6); } /** * @dev Creates a new Round of a paricular Tower * @param _TowerType the tower type (0 to 6) */ function newRound (uint256 _TowerType) private { GameRounds[_TowerType].currentRoundID++; GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID] = TowersInfo(GameRounds[_TowerType].currentRoundID, 0, 0, 0, now+GameRounds[_TowerType].timeLimit, GameRounds[_TowerType].timeLimit, GameRounds[_TowerType].warriorToTime, GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID-1].towerBalance*GameRounds[_TowerType].nextRound/100, // Moving nextRound% of the finished round balance to the next round 0x0); // New round } /** * @dev Use to buy warriors for the current round of a particular Tower * When the Round ends, somebody have to buy 1 warrior to start the new round. * All ETH the player overpaid will be sent back to his balance ("referralBalance"). * @param _TowerType the tower type (0 to 6) * @param _WarriorsAmount the amoun of warriors player would like to buy (at least 1) * @param _referralID Default Value: 0. The ID of the player which will receive the 10% of the warriors cost. */ function buyWarriors (uint256 _TowerType, uint _WarriorsAmount, uint256 _referralID) public payable { require (msg.value > 10000000); // To prevent % abusing require (_WarriorsAmount >= 1 && _WarriorsAmount < 1000000000); // The limitation of the amount of warriors being bought in 1 time require (GameRounds[_TowerType].timeLimit > 0); // Checking if the _TowerType exists if (players[msg.sender].playerID == 0){ // this is the new player if (_referralID > 0 && _referralID != players[msg.sender].playerID && _referralID == playersByID[_referralID].playerID){ setNickname("", playersByID[_referralID].playerAddress); // Creating a new player... }else{ setNickname("", ownerAddress); } } if (GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeToFinish < now){ // The game was ended. Starting the new game... // Sending pot to the winner aff[GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].lastPlayer].balance += GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].towerBalance*GameRounds[_TowerType].winnerShare/100; // Sending the bonus pot to the winner aff[GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].lastPlayer].balance += GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].bonusPot; newRound(_TowerType); //Event Winner and the new round //return; } // Getting the price of the current warrior uint256 _totalWarriors = GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].totalWarriors; uint256 _warriorPrice = (_totalWarriors+1)*GameRounds[_TowerType].growthCoefficient; // Warrior Price uint256 _value = (_WarriorsAmount*_warriorPrice)+(((_WarriorsAmount-1)*(_WarriorsAmount-1)+_WarriorsAmount-1)/2)*GameRounds[_TowerType].growthCoefficient; require (msg.value >= _value); // Player pays enough uint256 _ethToTake = affShare+devShare; // 15% players[msg.sender].TowersList[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].warriors += _WarriorsAmount; if (players[players[msg.sender].referralAddress].playerID > 0 && players[msg.sender].referralAddress != ownerAddress){ // To referrer and devs. In this case, referrer gets 10%, devs get 5% aff[players[msg.sender].referralAddress].balance += _value*affShare/100; // 10% aff[ownerAddress].balance += _value*devShare/100; // 5% } else { // To devs only. In this case, devs get 10% _ethToTake = affShare; aff[ownerAddress].balance += _value*_ethToTake/100; // 10% } if (msg.value-_value > 0){ aff[msg.sender].balance += msg.value-_value; // Returning to player the rest of eth } GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].towerBalance += _value*(100-_ethToTake)/100; // 10-15% GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].totalBalance += _value; GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].totalWarriors += _WarriorsAmount; GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].lastPlayer = msg.sender; // Timer increasement GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeToFinish += (_WarriorsAmount).mul(GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].warriorToTime); // if the finish time is longer than the finish if (GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeToFinish > now+GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeLimit){ GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeToFinish = now+GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeLimit; } uint256 TotalWarriors = GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].totalWarriors; uint256 TimeLeft = GameRounds[_TowerType].RoundList[GameRounds[_TowerType].currentRoundID].timeToFinish; // Event about the new potential winner and some Tower Details emit BuyEvent(msg.sender, _TowerType, GameRounds[_TowerType].currentRoundID, TotalWarriors, (TotalWarriors+1)*GameRounds[_TowerType].growthCoefficient, TimeLeft); return; } /** * @dev Claim the player's dividends of any round. * @param _TowerType the tower type (0 to 6) * @param _RoundID the round ID */ function dividendCashout (uint256 _TowerType, uint256 _RoundID) public { require (GameRounds[_TowerType].timeLimit > 0); uint256 _warriors = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].warriors; require (_warriors > 0); uint256 _totalEarned = _warriors*GameRounds[_TowerType].RoundList[_RoundID].towerBalance*GameRounds[_TowerType].dividendShare/GameRounds[_TowerType].RoundList[_RoundID].totalWarriors/100; uint256 _alreadyCashedOut = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut; uint256 _earnedNow = _totalEarned-_alreadyCashedOut; require (_earnedNow > 0); // The total amount of dividends haven't been received by the player yet players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _totalEarned; if (!msg.sender.send(_earnedNow)){ players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _alreadyCashedOut; } return; } /** * @dev Claim the player's In-Game balance such as returnings and referral payings. */ function referralCashout () public { require (aff[msg.sender].balance > 0); uint256 _balance = aff[msg.sender].balance; aff[msg.sender].balance = 0; if (!msg.sender.send(_balance)){ aff[msg.sender].balance = _balance; } } /** * @dev Creates the new account * @param nickname the nickname player would like to use (better to leave it empty) * @param _referralAddress (the address of the player who invited the user) */ function setNickname (string nickname, address _referralAddress) public { if (players[msg.sender].playerID == 0){ players[msg.sender] = PlayerInfo (playerID_counter, msg.sender, _referralAddress, nickname); playersByID[playerID_counter] = PlayerInfo (playerID_counter, msg.sender, _referralAddress, nickname); playerID_counter++; }else{ players[msg.sender].nickname = nickname; playersByID[players[msg.sender].playerID].nickname = nickname; } } /** * @dev The following functions are for the web-site implementation to get details about Towers, Rounds and Players */ function _playerRoundsInfo (address _playerAddress, uint256 _TowerType, uint256 _RoundID) public view returns (uint256, uint256, uint256, uint256, bool, address) { uint256 _warriors = players[_playerAddress].TowersList[_TowerType].RoundList[_RoundID].warriors; TowersInfo memory r = GameRounds[_TowerType].RoundList[_RoundID]; bool isFinished = true; if (r.timeToFinish > now){ isFinished = false; } return ( r.towerBalance*GameRounds[_TowerType].winnerShare/100, _currentPlayerAmountUnclaimed(_playerAddress, _TowerType, _RoundID), _warriors, r.totalWarriors, isFinished, r.lastPlayer); } function _currentPlayerAmountUnclaimed (address _playerAddress, uint256 _TowerType, uint256 _RoundID) public view returns (uint256) { if (_RoundID == 0){ _RoundID = GameRounds[_TowerType].currentRoundID; } uint256 _warriors = players[_playerAddress].TowersList[_TowerType].RoundList[_RoundID].warriors; uint256 _totalForCashOut = (_warriors*GameRounds[_TowerType].RoundList[_RoundID].towerBalance*GameRounds[_TowerType].dividendShare/GameRounds[_TowerType].RoundList[_RoundID].totalWarriors/100); uint256 _unclaimedAmount = _totalForCashOut-players[_playerAddress].TowersList[_TowerType].RoundList[_RoundID].cashedOut; return (_unclaimedAmount); } function _playerInfo (uint256 _playerID) public view returns (uint256, address, string, uint256) { return (playersByID[_playerID].playerID, playersByID[_playerID].playerAddress, playersByID[_playerID].nickname, aff[playersByID[_playerID].playerAddress].balance); } function _playerBalance (address _playerAddress) public view returns (uint256) { return aff[_playerAddress].balance; } function _TowerRoundDetails (uint256 _TowerType, uint256 _RoundID) public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address) { TowersInfo memory r = GameRounds[_TowerType].RoundList[_RoundID]; return ( r.roundID, r.towerBalance, r.totalBalance, r.totalWarriors, r.timeToFinish, r.timeLimit, r.warriorToTime, r.bonusPot, r.lastPlayer ); } } 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; require(c / a == b, "SafeMath mul failed"); 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
To referrer and devs. In this case, referrer gets 10%, devs get 5% To devs only. In this case, devs get 10%
if (players[players[msg.sender].referralAddress].playerID > 0 && players[msg.sender].referralAddress != ownerAddress){ _ethToTake = affShare; }
1,048,731
[ 1, 774, 14502, 471, 4461, 87, 18, 657, 333, 648, 16, 14502, 5571, 1728, 9, 16, 4461, 87, 336, 1381, 9, 2974, 4461, 87, 1338, 18, 657, 333, 648, 16, 4461, 87, 336, 1728, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 1601, 414, 63, 1601, 414, 63, 3576, 18, 15330, 8009, 1734, 29084, 1887, 8009, 14872, 734, 405, 374, 597, 18115, 63, 3576, 18, 15330, 8009, 1734, 29084, 1887, 480, 3410, 1887, 15329, 203, 5411, 389, 546, 774, 13391, 273, 7103, 9535, 31, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xc54455e1Ac910e3e4Edd7dbdb8EA46F97f806E69/sources/MISOLiquidityLauncher.sol
@dev Get the total number of launchers in the contract
function numberOfLiquidityLauncherContracts() public view returns (uint256) { return launchers.length; }
16,860,351
[ 1, 967, 326, 2078, 1300, 434, 8037, 414, 316, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7922, 48, 18988, 24237, 28820, 20723, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 8037, 414, 18, 2469, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x09211B547063113cE09d42BF78830EC187e4a926/sources/Depor6DOSUserBook.sol
6upusers add level count
function doUserLevelUp(address _addr) internal { User storage user = addrToUser[_addr]; if (user.userId == 0) { return; } user.level++; uint256[] memory upInviteUserIds = user.inviteUserIds; for (uint8 i = 0; i < upInviteUserIds.length; i++) { if (upInviteUserIds[i] != 0) { User memory upUser = userIdToUser[upInviteUserIds[i]]; doIncreaseLevelCount(upUser.addr, user.level); } continue; }
16,839,652
[ 1, 26, 416, 5577, 527, 1801, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 741, 1299, 2355, 1211, 12, 2867, 389, 4793, 13, 2713, 288, 203, 3639, 2177, 2502, 729, 273, 3091, 774, 1299, 63, 67, 4793, 15533, 203, 3639, 309, 261, 1355, 18, 18991, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 729, 18, 2815, 9904, 31, 203, 203, 3639, 2254, 5034, 8526, 3778, 731, 22730, 1299, 2673, 273, 729, 18, 27154, 1299, 2673, 31, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 731, 22730, 1299, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 416, 22730, 1299, 2673, 63, 77, 65, 480, 374, 13, 288, 203, 7734, 2177, 3778, 731, 1299, 273, 6249, 774, 1299, 63, 416, 22730, 1299, 2673, 63, 77, 13563, 31, 203, 7734, 741, 382, 11908, 2355, 1380, 12, 416, 1299, 18, 4793, 16, 729, 18, 2815, 1769, 203, 5411, 289, 203, 5411, 1324, 31, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x8f449Cdf6249E608c661c37eeA40420A117501DE/sources/KickstarterDepFee.sol
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. Example from CappedCrowdsale.sol's _preValidatePurchase method: super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= cap); @param beneficiary Address performing the token purchase @param weiAmount Value in wei involved in the purchase/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) virtual internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); }
8,266,783
[ 1, 4354, 434, 392, 6935, 23701, 18, 2672, 2583, 6317, 358, 15226, 919, 1347, 4636, 854, 486, 5100, 18, 2672, 1375, 9565, 68, 316, 20092, 716, 6811, 628, 385, 492, 2377, 5349, 358, 2133, 3675, 20808, 18, 5090, 628, 11200, 1845, 39, 492, 2377, 5349, 18, 18281, 1807, 389, 1484, 4270, 23164, 707, 30, 377, 2240, 6315, 1484, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 377, 2583, 12, 1814, 77, 12649, 5918, 7675, 1289, 12, 1814, 77, 6275, 13, 1648, 3523, 1769, 225, 27641, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 732, 77, 6275, 1445, 316, 732, 77, 24589, 316, 326, 23701, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1484, 4270, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 5024, 2713, 1476, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 27641, 74, 14463, 814, 353, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 1814, 77, 6275, 480, 374, 16, 315, 39, 492, 2377, 5349, 30, 732, 77, 6275, 353, 374, 8863, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x34cB8F75952dFbC5c40832745bcC851071aF8055/sources/MultiSigWallet.sol
@dev Returns total number of transactions after filers are applied. @param pending Include pending transactions. @param executed Include executed transactions. @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ( (pending && !transactions[i].executed) || (executed && transactions[i].executed) ) count += 1; }
9,427,970
[ 1, 1356, 2078, 1300, 434, 8938, 1839, 661, 414, 854, 6754, 18, 225, 4634, 12672, 4634, 8938, 18, 225, 7120, 12672, 7120, 8938, 18, 327, 10710, 1300, 434, 8938, 1839, 3415, 854, 6754, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 15674, 1380, 12, 6430, 4634, 16, 1426, 7120, 13, 203, 202, 202, 482, 203, 202, 202, 1945, 203, 202, 202, 6154, 261, 11890, 5034, 1056, 13, 203, 202, 95, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2492, 1380, 31, 277, 27245, 203, 1082, 202, 430, 261, 203, 9506, 202, 12, 9561, 597, 401, 20376, 63, 77, 8009, 4177, 4817, 13, 747, 203, 9506, 202, 12, 4177, 4817, 597, 8938, 63, 77, 8009, 4177, 4817, 13, 203, 1082, 202, 13, 1056, 1011, 404, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../models/_Interfaces.sol"; import "../libraries/SafeMath.sol"; import "../utils/ERC20_Utils.sol"; // This contract secures votes via locking of tokens in the contract abstract contract _LockVote is ERC20_Utils { address public owner; // contract deployer address public DeFiat_Gov; //governance contract bytes32 public voteName; // name to describe the vote uint256 public voteStart; // UTC timestamp for voteStart uint256 public voteEnd; // UTC timestamp for voteEnd bool public decisionActivated; // track whether decision has been activated uint256 public quorum; // x / 100 = required % of votes / voting power for vote to be actionable uint256 public totalVotes; // total votes cast uint256[] public voteChoices; // array of choices to vote for mapping (address => uint256) public votes; // address => user vote choice mapping (address => uint256) public votingTokens; // address => locked tokens address public votingPowerToken; address public rewardToken; uint256 public rewardAmount; event voteStarting(address _Defiat_Gov, uint256 _voteStart, uint256 _voteEnd, bytes32 _hash, bytes32 _voteName); modifier OnlyOwner() { require(msg.sender == owner); _; } modifier TokenHolder{ require(IERC20(votingPowerToken).balanceOf(msg.sender) > 0, "Only holders can vote"); _; } modifier VoteClosed() { require(now > voteEnd, "Vote is still open"); require(decisionActivated, "Vote decision must be activated"); _; } modifier VoteOpen() { require(now > voteStart, "Vote is not open"); require(now < voteEnd, "Voting has expired"); _; } modifier CanVote() { require(votes[msg.sender] == 0, "Already voted"); //block time has not been updated _; } modifier QuorumReached { require(totalVotes > IERC20(votingPowerToken).totalSupply() * (quorum / 100), "Not enough votes have been cast"); _; } constructor( address _DeFiat_Gov, uint256 _delayStartHours, uint256 _durationHours, bytes32 _voteName, uint256 _voteChoices, uint256 _quorum, address _votingPowerToken, address _rewardToken, uint256 _rewardAmount ) public { owner = msg.sender; DeFiat_Gov = _DeFiat_Gov; voteStart = block.timestamp + (_delayStartHours * 3600); voteEnd = voteStart + (_durationHours * 3600); voteName = _voteName; voteChoices = new uint256[](_voteChoices); rewardToken = _rewardToken; rewardAmount = _rewardAmount; votingPowerToken = _votingPowerToken; quorum = _quorum; decisionActivated = false; bytes32 _hash = sha256(abi.encodePacked(DeFiat_Gov, voteEnd)); emit voteStarting(DeFiat_Gov, voteStart, voteEnd, _hash, voteName); } // 0 - define virtual proposal action function // all new votes will override this method with the intended function to be activated on vote passing function proposalAction() public virtual returns (bool); //1- define ACTIVATION function function activateDecision() external { //anybody can activate this. require(voteEnd < now, "Voting still ongoing"); require(!decisionActivated, "Vote decision has already been activated"); decisionActivated = true; // mark decision activated proposalAction(); } function vote(uint voteChoice, uint256 votePower) external VoteOpen CanVote TokenHolder { require(voteChoice < voteChoices.length, "Invalid vote choice"); IERC20(votingPowerToken).transferFrom(msg.sender, address(this), votePower); // transfer tokens to contract votes[msg.sender] = voteChoice; // log of user vote votingTokens[msg.sender] = votingTokens[msg.sender] + votePower; // increase locked token pointer voteChoices[voteChoice] = voteChoices[voteChoice] + votePower; // increase vote count totalVotes = totalVotes + votePower; // increase total votes _sendReward(msg.sender); } //3- reward voters function _sendReward(address _address) internal { if(IERC20(rewardToken).balanceOf(address(this)) >= rewardAmount){ IERC20(rewardToken).transfer(_address, rewardAmount); } } //rewards if enough in the pool //4- claim tokens when vote is over function claimTokens() external VoteClosed { require(votingTokens[msg.sender] > 0, "No tokens to claim"); uint256 votingPower = votingTokens[msg.sender]; IERC20(votingPowerToken).transfer(msg.sender, votingPower); votingTokens[msg.sender] = votingTokens[msg.sender] - votingPower; } //0- Misc functions function forceVoteEnd() external OnlyOwner { voteEnd = now; } function forceDecision(bool _decision) external OnlyOwner { decisionActivated = _decision; } function myVotingPower(address _address) internal view returns(uint256) { // simple 1:1 token to vote uint256 _power = IERC20(votingPowerToken).balanceOf(_address); return _power; } } //end contract
track whether decision has been activated
bool public decisionActivated;
900,655
[ 1, 4101, 2856, 14604, 711, 2118, 14892, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1426, 1071, 14604, 28724, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD4dCcDB7515F4fE0fbBd9478c17C7d4fA3032e96/sources/Test.sol
Trade start checkSet Fee for BuysSet Fee for Sells
function _transfer( address from, address to, uint256 amount ) private onlyNonBlacklisted { 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"); require( amount <= balanceOf(from), "Transfer amount exceeds sender's balance" ); if (from != owner() && to != owner()) { if (!tradingOpen) { require( from == owner(), "TOKEN: This account cannot send tokens until trading is enabled" ); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if (to != uniswapV2Pair) { require( balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!" ); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to] ) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; (_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair) ) { takeFee = false; if (from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); }
4,182,444
[ 1, 22583, 787, 866, 694, 30174, 364, 605, 89, 1900, 694, 30174, 364, 348, 1165, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 1338, 3989, 13155, 18647, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 3639, 2583, 12, 203, 5411, 3844, 1648, 11013, 951, 12, 2080, 3631, 203, 5411, 315, 5912, 3844, 14399, 5793, 1807, 11013, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 288, 203, 5411, 309, 16051, 313, 14968, 3678, 13, 288, 203, 7734, 2583, 12, 203, 10792, 628, 422, 3410, 9334, 203, 10792, 315, 8412, 30, 1220, 2236, 2780, 1366, 2430, 3180, 1284, 7459, 353, 3696, 6, 203, 7734, 11272, 203, 5411, 289, 203, 203, 5411, 2583, 12, 8949, 1648, 389, 1896, 4188, 6275, 16, 315, 8412, 30, 4238, 5947, 7214, 8863, 203, 203, 5411, 309, 261, 869, 480, 640, 291, 91, 438, 58, 22, 4154, 13, 288, 203, 7734, 2583, 12, 203, 10792, 11013, 951, 12, 869, 13, 397, 3844, 411, 389, 1896, 16936, 1225, 16, 203, 10792, 315, 8412, 30, 30918, 14399, 9230, 963, 4442, 203, 7734, 11272, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2 ]
// // // ,╔φ▒╠▒▒▒ // ,φ╠░▒▒▒▒▒▒▒ // ,▒░░░░░▒▒▒▒▒▒ε // φ░░░░░░▒▒▒▒▒▒▒╠ // φ░░░░░░░▒▒▒▒▒▒▒╠ // ,≤φ░░░░░φφφ≡, ░░░░░░░▒▒▒▒▒▒▒▒╠ // ;φ░░░░░░░░░░░░░Γ «░░░░░░▒▒▒▒▒▒▒▒╠╠ // ;░░░░░░░░░░░░░░░░░[ )░░░░░▒▒▒▒▒▒▒▒▒╠╠ // ,░░░░░░░░░░░░░░░░░░░╠" ╙▒▒▒▒▒▒▒▒▒╠╠ // ≤░░░░░░░░░░░░░░░░░░░░╚ ╔╠░░φ, ▒▒▒▒▒▒▒╠╩ // ⁿ░░││││░░░░░░░░░░░░░ε ░░░░░▒ `╙╠▒▒╩ // "░'\││░░░░░░░░░░░░╚ `╙╩╩" ╓╓ // ""░░░░░░░≥=" ,- ,╔╠▒▒▒╠╦ // ,φ▒░░░▒▒▒▒▒▒▒▒▒▒╠╦ // ░░░░░░░▒▒▒▒▒▒▒▒▒╠╠╬ // `░░░░░▒▒▒▒▒▒▒▒╠╠╠╠╠╠ // "░░░░▒▒▒▒▒▒╠╠╠╠╠╠╠╠╬ // ╚░░▒▒▒▒╠╠╠╠╠╠╠╠╠╠╠ // "╩▒▒╠╠╠╠╠╠╠╠╠╠╠╠ // "╚╠╠╠╠╠╠╠╠╠╩ // "╙╝╠╠╩ // // // pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "./License.sol"; contract SunflowerArtV2 is Initializable, ERC721EnumerableUpgradeable, OwnableUpgradeable, PausableUpgradeable { string public artCode; string public artCodeDependencies; //e.g. [email protected] string public artDescription; bool public isArtCodeSealed; uint256 public currentTokenID; uint256 public maxTokens; uint256 public tokenPrice; string public tokenBaseURI; string public extraStringArtist; string public extraStringPlatform; // Address that can mint when paused, intended to be the address of another contract. address public privilegedMinterAddress; // address payable public artistFundsAddress; address public artistAddress; // Deployer address is the artist. uint256 private artistBalance; // For safety with arbitrary address, use withdrawal mechanism. address payable constant platformAddress = payable(0xf0bE1F2FB8abfa9aBF7d218a226ef4F046f09a40); uint256 public sunflowerMintPercent; // e.g. 10 for %10 uint256 public sunflowerTokenRoyalty; // e.g. 31 for every 31th token uint256 public artistTokenRoyalty; address constant public sunflowerPreviousVersionContractAddress = 0xD58434F33a20661f186ff67626ea6BDf41B80bCA; uint256 constant public sunflowerContractVersion = 2; // Block hashes are determined at mint time. // The seed corresponding to a token can only be accesed one block after, and is equal to keccak256(blockhash ^ tokenID) mapping(uint256 => bytes32) internal blockhashForToken; // Want "initialize" so can use proxy function initialize(string memory _name, string memory _symbol, uint256 _maxTokens, uint256 _tokenPrice, address _artistFundsAddress, uint256 _artistTokenRoyalty) public initializer { __ERC721_init(_name, _symbol); __ERC721Enumerable_init_unchained(); __Ownable_init(); __Pausable_init(); isArtCodeSealed = false; // Fixed, but can be adjusted for each proxy contract with setPlatformFields. sunflowerMintPercent = 29; sunflowerTokenRoyalty = 31; // Every 31th token, so 3.22%. Use a prime to reduce collisions. artistBalance = 0; tokenBaseURI = ""; // Use these methods so the checks of those methods will run. setArtistFields(_artistTokenRoyalty); setMaxTokens(_maxTokens); setTokenPrice(_tokenPrice); currentTokenID = 0; artistFundsAddress = payable(_artistFundsAddress); privilegedMinterAddress = address(0); artistAddress = owner(); // initialize to the deployer address, and don't let it be changed pauseNormalMinting(); } // Guarantee every seed is different, and make it impractical to predict, by XORing with tokenID. function seedForToken(uint256 tokenID) public view returns (uint256) { require(_exists(tokenID), "Nonexistant token"); bytes32 intermediate = bytes32(tokenID) ^ blockhashForToken[tokenID]; bytes32 hashed = keccak256(abi.encodePacked(intermediate)); uint256 seed = uint256(hashed); return seed; } // Base minting function. Ensures only maxTokens can ever be minted. MaxTokens can only be set before the contract is sealed. function _mintBase(address _recipient, uint256 _tokenID) internal { requireSealed(); require(_tokenID < maxTokens, "Max number of tokens minted"); _safeMint(_recipient, _tokenID); blockhashForToken[_tokenID] = blockhash(block.number - 1); } function _generalMint(address _recipient) internal { // Skip token if it's meant for platform or artist royalties. if (((sunflowerTokenRoyalty != 0) && ((currentTokenID % sunflowerTokenRoyalty) == 0)) || ((artistTokenRoyalty != 0) && ((currentTokenID % artistTokenRoyalty) == 0))) { currentTokenID = currentTokenID + 1; _generalMint(_recipient); return; } // Mint currentTokenID _mintBase(_recipient, currentTokenID); currentTokenID = currentTokenID + 1; // Handle payment require(msg.value == tokenPrice, "Tx value incorrect"); uint256 sunflowerFee = (sunflowerMintPercent * 100 * msg.value) / (100*100); uint256 artistAmount = msg.value - sunflowerFee; // Trusted address platformAddress.transfer(sunflowerFee); // Add to artist balance artistBalance += artistAmount; } function mintRoyalties() public { requireSealed(); require(currentTokenID >= maxTokens - 2, "Max tokens not yet reached"); if (artistTokenRoyalty != 0) { for (uint256 i =0; i<maxTokens; i+= artistTokenRoyalty) { // Avoid numbers where (i % sunflowerTokenRoyalty == 0) && (i % artistTokenRoyalty == 0) if ((i % sunflowerTokenRoyalty) != 0) { _mintBase(artistFundsAddress, i); } } } if (sunflowerTokenRoyalty != 0) { for (uint256 i =0; i<maxTokens; i+= sunflowerTokenRoyalty) { _mintBase(platformAddress, i); } } } // Standard minting function. Requires msg.value==tokenPrice and mintingNotPaused. function mintToken() public payable { requireMintingNotPaused(); _generalMint(msg.sender); } // Mint for owner, ignoring pause status. Requires msg.value==tokenPrice and owner. function mintTokenOwner() public payable { requireOwner(); _generalMint(msg.sender); } // Mintable by privilegedMinterAddress, ignoring pause status. function mintTokenPrivileged(address _recipient) public payable { require(privilegedMinterAddress != address(0)); require(msg.sender == privilegedMinterAddress); _generalMint(_recipient); } function withdrawArtistBalance() public { uint256 balanceToSend = artistBalance; artistBalance = 0; artistFundsAddress.transfer(balanceToSend); } // Pause and unpause function pauseNormalMinting() public { requireOwner(); _pause(); } function resumeNormalMinting() public { requireOwner(); _unpause(); } function requireMintingNotPaused() internal view whenNotPaused {} // Fields that are adjustable any time. function setTokenPrice(uint256 _tokenPrice) public { requireOwner(); tokenPrice = _tokenPrice; require(_tokenPrice == 0 || artistTokenRoyalty == 0); } function setPrivilegedMinterAddress(address _privilegedMinterAddress) public { // RequirePlatform requirePlatform(); privilegedMinterAddress = _privilegedMinterAddress; } // Fields that are only adjustable before sealing. function setPlatformFields(uint256 _sunflowerMintPercent, uint256 _sunflowerTokenRoyalty) public { requirePlatform(); requireNotSealed(); sunflowerMintPercent = _sunflowerMintPercent; sunflowerTokenRoyalty = _sunflowerTokenRoyalty; } function setArtistFields(uint256 _artistTokenRoyalty) public { requireOwner(); requireNotSealed(); require((_artistTokenRoyalty == 0) || (((_artistTokenRoyalty % sunflowerTokenRoyalty) != 0) && (_artistTokenRoyalty > 2)), "See requirements for artistTokenRoyalty"); artistTokenRoyalty = _artistTokenRoyalty; require(tokenPrice == 0 || _artistTokenRoyalty == 0); } function setMaxTokens(uint256 _maxTokens) public { requireOwner(); requireNotSealed(); maxTokens = _maxTokens; } function setArtCode(string memory _artCode, string memory _artCodeDependencies, string memory _artDescription) public { requireOwner(); requireNotSealed(); artCode = _artCode; artCodeDependencies = _artCodeDependencies; artDescription = _artDescription; } // Seal the art code. Disables many functions of the contract function sealArtCode() public { requireOwner(); requireNotSealed(); require((bytes(artCode).length != 0) && (bytes(artCodeDependencies).length != 0) && (bytes(artDescription).length != 0), "Art not fully set."); isArtCodeSealed = true; } function requireNotSealed() internal view { require(isArtCodeSealed == false, "Art is sealed"); } function requireSealed() internal view { require(isArtCodeSealed == true, "Art is not sealed"); } // Functions for token URI and other strings that provide extra context (e.g. social links that may change, IPFS links to contract ABI, etc.). Can be set anytime. function _baseURI() internal view override returns (string memory) { return tokenBaseURI; } function setBaseURI(string memory _tokenBaseURI) public { requireOwner(); tokenBaseURI = _tokenBaseURI; } function setExtraStringArtist(string memory _extraStringArtist) public { requireOwner(); extraStringArtist = _extraStringArtist; } function setExtraStringPlatform(string memory _extraStringPlatform) public { requirePlatform(); extraStringPlatform = _extraStringPlatform; } // Convert any modifiers to require functions, for readability. function requireOwner() internal view onlyOwner {} function requirePlatform() internal view { require(platformAddress == msg.sender, "Platform only"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^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.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/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 { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 {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. */ 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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/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.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 { 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 _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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.ownerOf(tokenId), 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()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @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.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^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; 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 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 pragma solidity ^0.8.0; import "../proxy/utils/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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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 IERC165Upgradeable { /** * @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.8.0; import "../../utils/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.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); } // The MIT License (MIT) // // // // 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.
Deployer address is the artist.
address public artistAddress;
538,054
[ 1, 10015, 264, 1758, 353, 326, 15469, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1758, 1071, 15469, 1887, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @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 { 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 _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 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(to).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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/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.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.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @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(); } } // SPDX-License-Identifier: MIT pragma solidity ^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.8.0; import "../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); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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 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); } } // SPDX-License-Identifier: MIT 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 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 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]; } // 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.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoyalties.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / Enumerable / URIStorage / Royalties /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721Burnable, ERC721WithRoyalties { /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721, ERC721WithRoyalties) returns (bool) { return // either ERC721Enumerable ERC721Enumerable.supportsInterface(interfaceId) || // or Royalties ERC721WithRoyalties.supportsInterface(interfaceId); } /// @inheritdoc ERC721 function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721, ERC721Ownable) returns (bool) { return ERC721Ownable.isApprovedForAll(owner_, operator); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea { /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_ ) ERC721(name_, symbol_) { // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea if (isOwnersOpenSeaProxy(owner, operator)) { return true; } return super.isApprovedForAll(owner, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyOwner { _setContractURI(contractURI_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../Royalties/ERC2981/IERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is IERC2981Royalties, IRaribleSecondarySales { function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256) public view virtual override returns (address _receiver, uint256 _royaltyAmount) { _receiver = address(this); _royaltyAmount = 0; } /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IRenderer /// @author Simon Fremaux (@dievardump) interface IRenderer { /// @dev Rendering function; /// @param name the seedling name /// @param tokenId the tokenId /// @param seed the seed /// @return the json function render( string memory name, uint256 tokenId, bytes32 seed ) external pure returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title IVariety interface /// @author Simon Fremaux (@dievardump) interface IVariety is IERC721 { /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external returns (uint256); /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32); /// @notice This function allows an owner to ask for a seed update /// this can be needed because although I test the contract as much as possible, /// it might be possible that one token does not render because the seed creates /// error or even "out of gas" computation. That's why this would allow an owner /// in such case, to request for a seed change that will then be triggered by Sower /// @param tokenId id to regenerate seed for function requestSeedChange(uint256 tokenId) external; /// @notice This function allows Sower to answer to a seed change request /// in the event where a seed would produce errors of rendering /// 1) this function can only be called by Sower if the token owner /// asked for a new seed /// 2) this function will only be called if there is a rendering error /// or, Vitalik Buterin forbid, a duplicate /// @param tokenId id to regenerate seed for function changeSeedAfterRequest(uint256 tokenId) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//////************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/////*******************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///***********************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**************************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**********/**************/*@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///////****/****************//@@@@@ // @@@*********@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(///////////*****************//@@@@@@ // @@@**************//////@@@@@@@@@@@@@@@@@@@((////////////***************//@@@@@@@ // @@@*********************////@@@@@@@@@@@@@((///////////////************//@@@@@@@@ // @@@@//**************//***//////@@@@@@@@@@(///////////////////*******//@@@@@@@@@@ // @@@@@/*****************////////((@@@@@@@((///((////////////////***//@@@@@@@@@@@@ // @@@@@@//*************////////////((@@@@@((//((////////////////////@@@@@@@@@@@@@@ // @@@@@@@//**********///////////////((@@@@((((//////////////////@@@@@@@@@@@@@@@@@@ // @@@@@@@@///******//////////////((//((@@@(((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@//*///////////////////(//((@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@////////////////////(((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@/((((/////////////((((/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@((((((((@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@###(((((((((((((((((((((((((###@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@####################################@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@#############################################@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import './IVariety.sol'; import '../NFT/ERC721Helpers/ERC721Full.sol'; /// @title Variety Contract /// @author Simon Fremaux (@dievardump) contract Variety is IVariety, ERC721Full { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); // seedlings Sower address public sower; // last tokenId uint256 public lastTokenId; // each token seed mapping(uint256 => bytes32) internal tokenSeed; // names mapping(uint256 => string) public names; // useNames mapping(bytes32 => bool) public usedNames; // tokenIds with a request for seeds change mapping(uint256 => bool) internal seedChangeRequests; modifier onlySower() { require(msg.sender == sower, 'Not Sower.'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_ ) ERC721Ownable(name_, symbol_, contractURI_, openseaProxyRegistry_) { sower = sower_; } /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external virtual override onlySower returns (uint256) { uint256 tokenId = lastTokenId; for (uint256 i; i < seeds.length; i++) { tokenId++; _safeMint(to, tokenId); tokenSeed[tokenId] = seeds[i]; } lastTokenId = tokenId; return tokenId; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Full, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, tokenSeed[tokenId]); } /// @notice ERC2981 support - 4% royalties sent to Sower /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { receiver = sower; royaltyAmount = (value * 400) / 10000; } /// @inheritdoc IVariety function getTokenSeed(uint256 tokenId) external view override returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return tokenSeed[tokenId]; } /// @inheritdoc IVariety function requestSeedChange(uint256 tokenId) external override { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// @inheritdoc IVariety function changeSeedAfterRequest(uint256 tokenId) external override onlySower { require(seedChangeRequests[tokenId] == true, 'No request for token.'); seedChangeRequests[tokenId] = false; tokenSeed[tokenId] = keccak256( abi.encode( tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external virtual { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); bytes32 byteName = keccak256(abi.encodePacked(seedlingName)); // if the name is not empty, verify it is not used if (bytes(seedlingName).length > 0) { require(usedNames[byteName] == false, 'Name already used'); usedNames[byteName] = true; } // if it already has a name, mark all name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { byteName = keccak256(abi.encodePacked(oldName)); usedNames[byteName] = false; } names[tokenId] = seedlingName; } /// @notice function to get a token name /// @dev token must exist /// @param tokenId the token to get the name of /// @return the token name function getName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), 'Unknown token'); return _getName(tokenId); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return the token name function _getName(uint256 tokenId) internal view virtual returns (string memory) { return bytes(names[tokenId]).length > 0 ? names[tokenId] : 'Variety'; } /// @notice Function allowing to check the rendering for a given seed /// This allows to know what a seed would render without minting /// @param seed the seed to render /// @return the json function renderSeed(bytes32 seed) public view returns (string memory) { return _render(0, seed); } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json;utf8,{"name":"', _getName(tokenId), '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Variety.sol'; /// @title VarietyRepot Contract /// @author Simon Fremaux (@dievardump) contract VarietyRepot is Variety { event SeedlingsRepoted(address user, uint256[] ids); // this is the address we will repot tokens from address public oldVariety; // during the first 3 days after the start of migration // we do not allow people to name, so people with names // in the old contract have time to migrate with theirs uint256 public disabledNamingUntil; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address oldVariety_ ) Variety(name_, symbol_, contractURI_, openseaProxyRegistry_, sower_) { sower = sower_; if (address(0) != oldVariety_) { oldVariety = oldVariety_; } // during 3 days, naming will be disabled as to give time to people to migrate from the old contract // to the new and keep their name disabledNamingUntil = block.timestamp + 3 days; } /// @inheritdoc Variety function plant(address, bytes32[] memory) external view override onlySower returns (uint256) { // this ensure that noone, even Sower, can directly mint tokens on this contract // they can only be created through the repoting method revert('No direct planting, only repot.'); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external override { require( block.timestamp > disabledNamingUntil, 'Naming feature disabled.' ); require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _setName(tokenId, seedlingName); } /// @notice Checks if the string is valid (0-9a-zA-Z,- ) with no leading, trailing or consecutives spaces /// This function is a modified version of the one in the Hashmasks contract /// @dev Explain to a developer any extra details /// @param str the name to validate /// @return if the name is valid function isNameValid(string memory str) public pure returns (bool) { bytes memory strBytes = bytes(str); if (strBytes.length < 1) return false; if (strBytes.length > 32) return false; // Cannot be longer than 32 characters if (strBytes[0] == 0x20) return false; // Leading space if (strBytes[strBytes.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar; bytes1 char; uint8 charCode; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces charCode = uint8(char); if ( !(charCode >= 97 && charCode <= 122) && // a - z !(charCode >= 65 && charCode <= 90) && // A - Z !(charCode >= 48 && charCode <= 57) && // 0 - 9 !(charCode == 32) && // space !(charCode == 44) && // , !(charCode == 45) // - ) { return false; } lastChar = char; } return true; } /// @notice Slugify a name (tolower and replace all non 0-9az by -) /// @param str the string to keyIfy /// @return the key function slugify(string memory str) public pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory lowerCase = new bytes(strBytes.length); uint8 charCode; bytes1 char; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; charCode = uint8(char); // if 0-9, a-z use the character if ( (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 122) ) { lowerCase[i] = char; } else if (charCode >= 65 && charCode <= 90) { // if A-Z, use lowercase lowerCase[i] = bytes1(charCode + 32); } else { // for all others, return a - lowerCase[i] = 0x2D; } } return string(lowerCase); } /// @notice repot (migrate and burn) the seedlings of `users` from the old variety contract to the new one /// to give them the exact same token id, seed and custom name if valid, on this contract /// The old token is burned (deleted) forever from the old contract /// @dev we do not need to check that `user` we transferFrom is not the current contract, because _safeMint /// would fail if we tried to mint the same tokenId twice /// @param users an array of users /// @param maxTokensAtOnce a limit of token to migrate at once, since a few users have strong hands function repotUsersSeedlings( address[] memory users, uint256 maxTokensAtOnce ) external { require( // only the contract owner msg.sender == owner() || // or someone trying to migrate their own tokens can call this function (users.length == 1 && users[0] == msg.sender), 'Not allowed to migrate.' ); Variety oldVariety_ = Variety(oldVariety); address me = address(this); address user; uint256 migrated; for (uint256 j; j < users.length && (migrated < maxTokensAtOnce); j++) { user = users[j]; uint256 userBalance = oldVariety_.balanceOf(user); if (userBalance == 0) continue; uint256 end = userBalance; // some users might have too many tokens to do that in one transaction if (userBalance > (maxTokensAtOnce - migrated)) { end = (maxTokensAtOnce - migrated); } uint256[] memory ids = new uint256[](end); uint256 tokenId; bytes32 seed; bytes32 slugBytes; string memory seedlingName; for (uint256 i; i < end; i++) { // get the last token id owned by the user // this is a bit cheaper than always getting index 0 // because when removing last there is no "reorg" in the EnumerableSet tokenId = oldVariety_.tokenOfOwnerByIndex( user, userBalance - (i + 1) // this takes the last id in the user list ); // get the token seed seed = oldVariety_.getTokenSeed(tokenId); // get the token name seedlingName = oldVariety_.getName(tokenId); // burn the old token first oldVariety_.burn(tokenId); // create the same token id in this contract for this user _safeMint(user, tokenId, ''); // set exact same seed tokenSeed[tokenId] = seed; // if the seedling had a name and the name is valid if ( bytes(seedlingName).length > 0 && isNameValid(seedlingName) ) { slugBytes = keccak256(bytes(slugify(seedlingName))); // and is not already used if (!usedNames[slugBytes]) { // then use it usedNames[slugBytes] = true; names[tokenId] = seedlingName; } } ids[i] = tokenId; } migrated += end; emit SeedlingsRepoted(user, ids); } } /// @dev allows to set a name internally. /// checks that the name is valid and not used, else throws /// @param tokenId the token to name /// @param seedlingName the name function _setName(uint256 tokenId, string memory seedlingName) internal { bytes32 slugBytes; // if the name is not empty, require that it's valid and not used if (bytes(seedlingName).length > 0) { require(isNameValid(seedlingName) == true, 'Invalid name.'); // also requires the name is not already used slugBytes = keccak256(bytes(slugify(seedlingName))); require(usedNames[slugBytes] == false, 'Name already used.'); // set as used usedNames[slugBytes] = true; } // if it already has a name, mark the old name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { slugBytes = keccak256(bytes(slugify(oldName))); usedNames[slugBytes] = false; } names[tokenId] = seedlingName; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../VarietyRepot.sol'; import '../IRenderer.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; /// @title _512PrintRepot /// @author Simon Fremaux (@dievardump) contract _512PrintRepot is VarietyRepot { using Strings for uint256; IRenderer public renderer; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract /// @param renderer_ the renderer contract /// @param oldContract_ the oldContract for migration constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address renderer_, address oldContract_ ) VarietyRepot( name_, symbol_, contractURI_, openseaProxyRegistry_, sower_, oldContract_ ) { renderer = IRenderer(renderer_); } /// @notice This function is a function that allows to update the current renderer /// to a version where "rounded-stroke-gradient" misprints are fixed /// this function will only be called in the case of a positive vote from 512Print holders function updateRenderer(address newRenderer) external onlyOwner { renderer = IRenderer(newRenderer); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return seedlingName the token name function _getName(uint256 tokenId) internal view override returns (string memory seedlingName) { seedlingName = names[tokenId]; if (bytes(seedlingName).length == 0) { seedlingName = string( abi.encodePacked('512Print.sol #', tokenId.toString()) ); } } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual override returns (string memory) { return IRenderer(renderer).render(_getName(tokenId), tokenId, seed); } }
@notice Checks if the string is valid (0-9a-zA-Z,- ) with no leading, trailing or consecutives spaces This function is a modified version of the one in the Hashmasks contract @dev Explain to a developer any extra details @param str the name to validate @return if the name is valid
function isNameValid(string memory str) public pure returns (bool) { bytes memory strBytes = bytes(str); if (strBytes.length < 1) return false; bytes1 lastChar; bytes1 char; uint8 charCode; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; charCode = uint8(char); if ( ) { return false; } lastChar = char; } return true; }
10,311,291
[ 1, 4081, 309, 326, 533, 353, 923, 261, 20, 17, 29, 69, 17, 9600, 17, 62, 16, 17, 262, 598, 1158, 7676, 16, 7341, 578, 356, 15166, 3606, 7292, 540, 1220, 445, 353, 279, 4358, 1177, 434, 326, 1245, 316, 326, 2474, 29102, 6835, 225, 1312, 7446, 358, 279, 8751, 1281, 2870, 3189, 225, 609, 326, 508, 358, 1954, 327, 309, 326, 508, 353, 923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30430, 1556, 12, 1080, 3778, 609, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 3778, 609, 2160, 273, 1731, 12, 701, 1769, 203, 3639, 309, 261, 701, 2160, 18, 2469, 411, 404, 13, 327, 629, 31, 203, 203, 3639, 1731, 21, 23914, 31, 203, 3639, 1731, 21, 1149, 31, 203, 3639, 2254, 28, 13096, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 609, 2160, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1149, 273, 609, 2160, 63, 77, 15533, 203, 5411, 13096, 273, 2254, 28, 12, 3001, 1769, 203, 203, 5411, 309, 261, 203, 5411, 262, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 203, 5411, 23914, 273, 1149, 31, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only // Copyright 2020 Compound Labs, Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. pragma solidity ^0.7.5; pragma experimental ABIEncoderV2; contract RadicleToken { /// @notice EIP-20 token name for this token string public constant NAME = "Radicle"; /// @notice EIP-20 token symbol for this token string public constant SYMBOL = "RAD"; /// @notice EIP-20 token decimals for this token uint8 public constant DECIMALS = 18; /// @notice Total number of tokens in circulation uint256 public totalSupply = 100000000e18; // 100 million tokens // Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; // 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 EIP-2612 permit 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 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 token * @param account The initial account to grant all the tokens */ constructor(address account) { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /* @notice Token name */ function name() public pure returns (string memory) { return NAME; } /* @notice Token symbol */ function symbol() public pure returns (string memory) { return SYMBOL; } /* @notice Token decimals */ function decimals() public pure returns (uint8) { return DECIMALS; } /* @notice domainSeparator */ // solhint-disable func-name-mixedcase function DOMAIN_SEPARATOR() public view returns (bytes32) { return keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), getChainId(), address(this)) ); } /** * @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) { _approve(msg.sender, spender, rawAmount); return true; } function _approve( address owner, address spender, uint256 rawAmount ) internal { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "RadicleToken::approve: amount exceeds 96 bits"); } 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, "RadicleToken::transfer: 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, "RadicleToken::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Burn `rawAmount` tokens from `account` * @param account The address of the account to burn * @param rawAmount The number of tokens to burn */ function burnFrom(address account, uint256 rawAmount) public { require(account != address(0), "RadicleToken::burnFrom: cannot burn from the zero address"); uint96 amount = safe96(rawAmount, "RadicleToken::burnFrom: amount exceeds 96 bits"); address spender = msg.sender; uint96 spenderAllowance = allowances[account][spender]; if (spender != account && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::burnFrom: burn amount exceeds allowance" ); allowances[account][spender] = newAllowance; emit Approval(account, spender, newAllowance); } balances[account] = sub96( balances[account], amount, "RadicleToken::burnFrom: burn amount exceeds balance" ); emit Transfer(account, address(0), amount); _moveDelegates(delegates[account], address(0), amount); totalSupply -= rawAmount; } /** * @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 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RadicleToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RadicleToken::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "RadicleToken::delegateBySig: signature expired"); _delegate(signatory, delegatee); } /** * @notice Approves spender to spend on behalf of owner. * @param owner The signer of the permit * @param spender The address to approve * @param deadline The time at which the signature expires * @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 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash)); require(owner == ecrecover(digest, v, r, s), "RadicleToken::permit: invalid signature"); require(owner != address(0), "RadicleToken::permit: invalid signature"); require(block.timestamp <= deadline, "RadicleToken::permit: signature expired"); _approve(owner, spender, value); } /** * @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, "RadicleToken::getPriorVotes: 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), "RadicleToken::_transferTokens: cannot transfer from the zero address" ); require( dst != address(0), "RadicleToken::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "RadicleToken::_transferTokens: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "RadicleToken::_transferTokens: 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, "RadicleToken::_moveVotes: 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, "RadicleToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "RadicleToken::_writeCheckpoint: 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 pure returns (uint256) { uint256 chainId; // solhint-disable no-inline-assembly assembly { chainId := chainid() } return chainId; } }
Allowance amounts on behalf of others Official record of token balances for each account
contract RadicleToken { string public constant NAME = "Radicle"; string public constant SYMBOL = "RAD"; uint8 public constant DECIMALS = 18; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; mapping(address => address) public delegates; struct Checkpoint { uint32 fromBlock; uint96 votes; } keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); address indexed delegate, uint256 previousBalance, uint256 newBalance ); mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = bytes32 public constant DELEGATION_TYPEHASH = bytes32 public constant PERMIT_TYPEHASH = mapping(address => uint256) public nonces; event DelegateChanged( event DelegateVotesChanged( event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); constructor(address account) { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function decimals() public pure returns (uint8) { return DECIMALS; } function DOMAIN_SEPARATOR() public view returns (bytes32) { return keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), getChainId(), address(this)) ); } function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } function approve(address spender, uint256 rawAmount) external returns (bool) { _approve(msg.sender, spender, rawAmount); return true; } function _approve( address owner, address spender, uint256 rawAmount ) internal { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "RadicleToken::approve: amount exceeds 96 bits"); } allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approve( address owner, address spender, uint256 rawAmount ) internal { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "RadicleToken::approve: amount exceeds 96 bits"); } allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } else { function balanceOf(address account) external view returns (uint256) { return balances[account]; } function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "RadicleToken::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "RadicleToken::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "RadicleToken::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function burnFrom(address account, uint256 rawAmount) public { require(account != address(0), "RadicleToken::burnFrom: cannot burn from the zero address"); uint96 amount = safe96(rawAmount, "RadicleToken::burnFrom: amount exceeds 96 bits"); address spender = msg.sender; uint96 spenderAllowance = allowances[account][spender]; if (spender != account && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::burnFrom: burn amount exceeds allowance" ); allowances[account][spender] = newAllowance; emit Approval(account, spender, newAllowance); } balances[account] = sub96( balances[account], amount, "RadicleToken::burnFrom: burn amount exceeds balance" ); emit Transfer(account, address(0), amount); _moveDelegates(delegates[account], address(0), amount); totalSupply -= rawAmount; } function burnFrom(address account, uint256 rawAmount) public { require(account != address(0), "RadicleToken::burnFrom: cannot burn from the zero address"); uint96 amount = safe96(rawAmount, "RadicleToken::burnFrom: amount exceeds 96 bits"); address spender = msg.sender; uint96 spenderAllowance = allowances[account][spender]; if (spender != account && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "RadicleToken::burnFrom: burn amount exceeds allowance" ); allowances[account][spender] = newAllowance; emit Approval(account, spender, newAllowance); } balances[account] = sub96( balances[account], amount, "RadicleToken::burnFrom: burn amount exceeds balance" ); emit Transfer(account, address(0), amount); _moveDelegates(delegates[account], address(0), amount); totalSupply -= rawAmount; } function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RadicleToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RadicleToken::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "RadicleToken::delegateBySig: signature expired"); _delegate(signatory, delegatee); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash)); require(owner == ecrecover(digest, v, r, s), "RadicleToken::permit: invalid signature"); require(owner != address(0), "RadicleToken::permit: invalid signature"); require(block.timestamp <= deadline, "RadicleToken::permit: signature expired"); _approve(owner, spender, value); } function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RadicleToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { 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), "RadicleToken::_transferTokens: cannot transfer from the zero address" ); require( dst != address(0), "RadicleToken::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "RadicleToken::_transferTokens: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "RadicleToken::_transferTokens: 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, "RadicleToken::_moveVotes: 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, "RadicleToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } 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, "RadicleToken::_moveVotes: 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, "RadicleToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } 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, "RadicleToken::_moveVotes: 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, "RadicleToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } 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, "RadicleToken::_moveVotes: 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, "RadicleToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "RadicleToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "RadicleToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { 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 pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
6,450,924
[ 1, 7009, 1359, 30980, 603, 12433, 6186, 434, 10654, 531, 4493, 649, 1409, 434, 1147, 324, 26488, 364, 1517, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16378, 3711, 1345, 288, 203, 565, 533, 1071, 5381, 6048, 273, 315, 6621, 3711, 14432, 203, 203, 565, 533, 1071, 5381, 26059, 273, 315, 28829, 14432, 203, 203, 565, 2254, 28, 1071, 5381, 25429, 55, 273, 6549, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 10525, 3719, 2713, 1699, 6872, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 10525, 13, 2713, 324, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 22310, 31, 203, 203, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 10525, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 3639, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 203, 3639, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 203, 3639, 417, 24410, 581, 5034, 12, 203, 5411, 315, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 203, 3639, 11272, 203, 203, 3639, 1758, 8808, 11158, 639, 16, 203, 3639, 1758, 8808, 628, 9586, 16, 203, 3639, 1758, 8808, 358, 9586, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 7152, 16, 203, 3639, 2254, 5034, 2416, 13937, 16, 203, 3639, 2254, 5034, 394, 13937, 203, 565, 11272, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../governance/Managed.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./DisputeManagerStorage.sol"; import "./IDisputeManager.sol"; /* * @title DisputeManager * @dev Provides a way to align the incentives of participants by having slashing as deterrent * for incorrect behaviour. * * There are two types of disputes that can be created: Query disputes and Indexing disputes. * * Query Disputes: * Graph nodes receive queries and return responses with signed receipts called attestations. * An attestation can be disputed if the consumer thinks the query response was invalid. * Indexers use the derived private key for an allocation to sign attestations. * * Indexing Disputes: * Indexers present a Proof of Indexing (POI) when they close allocations to prove * they were indexing a subgraph. The Staking contract emits that proof with the format * keccak256(indexer.address, POI). * Any challenger can dispute the validity of a POI by submitting a dispute to this contract * along with a deposit. * * Arbitration: * Disputes can only be accepted, rejected or drawn by the arbitrator role that can be delegated * to a EOA or DAO. */ contract DisputeManager is DisputeManagerV1Storage, GraphUpgradeable, IDisputeManager { using SafeMath for uint256; // -- EIP-712 -- bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Protocol"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0xa070ffb1cd7409649bf77822cce74495468e06dbfaef09556838bf188679b9c2; bytes32 private constant RECEIPT_TYPE_HASH = keccak256( "Receipt(bytes32 requestCID,bytes32 responseCID,bytes32 subgraphDeploymentID)" ); // -- Constants -- uint256 private constant ATTESTATION_SIZE_BYTES = 161; uint256 private constant RECEIPT_SIZE_BYTES = 96; uint256 private constant SIG_R_LENGTH = 32; uint256 private constant SIG_S_LENGTH = 32; uint256 private constant SIG_R_OFFSET = RECEIPT_SIZE_BYTES; uint256 private constant SIG_S_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH; uint256 private constant SIG_V_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH + SIG_S_LENGTH; uint256 private constant UINT8_BYTE_LENGTH = 1; uint256 private constant BYTES32_BYTE_LENGTH = 32; uint256 private constant MAX_PPM = 1000000; // 100% in parts per million // -- Events -- /** * @dev Emitted when a query dispute is created for `subgraphDeploymentID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman and `attestation` submitted. */ event QueryDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, bytes32 subgraphDeploymentID, bytes attestation ); /** * @dev Emitted when an indexing dispute is created for `allocationID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman. */ event IndexingDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, address allocationID ); /** * @dev Emitted when arbitrator accepts a `disputeID` to `indexer` created by `fisherman`. * The event emits the amount `tokens` transferred to the fisherman, the deposit plus reward. */ event DisputeAccepted( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator rejects a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` burned from the fisherman deposit. */ event DisputeRejected( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator draw a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` used as deposit and returned to the fisherman. */ event DisputeDrawn( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when two disputes are in conflict to link them. * This event will be emitted after each DisputeCreated event is emitted * for each of the individual disputes. */ event DisputeLinked(bytes32 indexed disputeID1, bytes32 indexed disputeID2); /** * @dev Check if the caller is the arbitrator. */ modifier onlyArbitrator { require(msg.sender == arbitrator, "Caller is not the Arbitrator"); _; } /** * @dev Initialize this contract. * @param _arbitrator Arbitrator role * @param _minimumDeposit Minimum deposit required to create a Dispute * @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) * @param _slashingPercentage Percentage of indexer stake slashed (ppm) */ function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); // Settings _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function setArbitrator(address _arbitrator) external override onlyGovernor { _setArbitrator(_arbitrator); } /** * @dev Internal: Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function _setArbitrator(address _arbitrator) private { require(_arbitrator != address(0), "Arbitrator must be set"); arbitrator = _arbitrator; emit ParameterUpdated("arbitrator"); } /** * @dev Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function setMinimumDeposit(uint256 _minimumDeposit) external override onlyGovernor { _setMinimumDeposit(_minimumDeposit); } /** * @dev Internal: Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); } /** * @dev Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function setFishermanRewardPercentage(uint32 _percentage) external override onlyGovernor { _setFishermanRewardPercentage(_percentage); } /** * @dev Internal: Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function _setFishermanRewardPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Reward percentage must be below or equal to MAX_PPM"); fishermanRewardPercentage = _percentage; emit ParameterUpdated("fishermanRewardPercentage"); } /** * @dev Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function setSlashingPercentage(uint32 _percentage) external override onlyGovernor { _setSlashingPercentage(_percentage); } /** * @dev Internal: Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function _setSlashingPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Slashing percentage must be below or equal to MAX_PPM"); slashingPercentage = _percentage; emit ParameterUpdated("slashingPercentage"); } /** * @dev Return whether a dispute exists or not. * @notice Return if dispute with ID `_disputeID` exists * @param _disputeID True if dispute already exists */ function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); } /** * @dev Get the message hash that an indexer used to sign the receipt. * Encodes a receipt using a domain separator, as described on * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification. * @notice Return the message hash used to sign the receipt * @param _receipt Receipt returned by indexer and submitted by fisherman * @return Message hash used to sign the receipt */ function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", // EIP-191 encoding pad, EIP-712 version 1 DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) // EIP 712-encoded message hash ) ) ); } /** * @dev Returns if two attestations are conflicting. * Everything must match except for the responseID. * @param _attestation1 Attestation * @param _attestation2 Attestation * @return True if the two attestations are conflicting */ function areConflictingAttestations( Attestation memory _attestation1, Attestation memory _attestation2 ) public override pure returns (bool) { return (_attestation1.requestCID == _attestation2.requestCID && _attestation1.subgraphDeploymentID == _attestation2.subgraphDeploymentID && _attestation1.responseCID != _attestation2.responseCID); } /** * @dev Returns the indexer that signed an attestation. * @param _attestation Attestation * @return Indexer address */ function getAttestationIndexer(Attestation memory _attestation) public override view returns (address) { // Get attestation signer, allocationID address allocationID = _recoverAttestationSigner(_attestation); IStaking.Allocation memory alloc = staking().getAllocation(allocationID); require(alloc.indexer != address(0), "Indexer cannot be found for the attestation"); require( alloc.subgraphDeploymentID == _attestation.subgraphDeploymentID, "Allocation and attestation subgraphDeploymentID must match" ); return alloc.indexer; } /** * @dev Get the fisherman reward for a given indexer stake. * @notice Return the fisherman reward based on the `_indexer` stake * @param _indexer Indexer to be slashed * @return Reward calculated as percentage of the indexer slashed funds */ function getTokensToReward(address _indexer) public override view returns (uint256) { uint256 tokens = getTokensToSlash(_indexer); if (tokens == 0) { return 0; } return uint256(fishermanRewardPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Get the amount of tokens to slash for an indexer based on the current stake. * @param _indexer Address of the indexer * @return Amount of tokens to slash */ function getTokensToSlash(address _indexer) public override view returns (uint256) { uint256 tokens = staking().getIndexerStakedTokens(_indexer); // slashable tokens if (tokens == 0) { return 0; } return uint256(slashingPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Create a query dispute for the arbitrator to resolve. * This function is called by a fisherman that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _attestationData Attestation bytes submitted by the fisherman * @param _deposit Amount of tokens staked as deposit */ function createQueryDispute(bytes calldata _attestationData, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createQueryDisputeWithAttestation( msg.sender, _deposit, _parseAttestation(_attestationData), _attestationData ); } /** * @dev Create query disputes for two conflicting attestations. * A conflicting attestation is a proof presented by two different indexers * where for the same request on a subgraph the response is different. * For this type of dispute the submitter is not required to present a deposit * as one of the attestation is considered to be right. * Two linked disputes will be created and if the arbitrator resolve one, the other * one will be automatically resolved. * @param _attestationData1 First attestation data submitted * @param _attestationData2 Second attestation data submitted * @return DisputeID1, DisputeID2 */ function createQueryDisputeConflict( bytes calldata _attestationData1, bytes calldata _attestationData2 ) external override returns (bytes32, bytes32) { address fisherman = msg.sender; // Parse each attestation Attestation memory attestation1 = _parseAttestation(_attestationData1); Attestation memory attestation2 = _parseAttestation(_attestationData2); // Test that attestations are conflicting require( areConflictingAttestations(attestation1, attestation2), "Attestations must be in conflict" ); // Create the disputes // The deposit is zero for conflicting attestations bytes32 dID1 = _createQueryDisputeWithAttestation( fisherman, 0, attestation1, _attestationData1 ); bytes32 dID2 = _createQueryDisputeWithAttestation( fisherman, 0, attestation2, _attestationData2 ); // Store the linked disputes to be resolved disputes[dID1].relatedDisputeID = dID2; disputes[dID2].relatedDisputeID = dID1; // Emit event that links the two created disputes emit DisputeLinked(dID1, dID2); return (dID1, dID2); } /** * @dev Create a query dispute passing the parsed attestation. * To be used in createQueryDispute() and createQueryDisputeConflict() * to avoid calling parseAttestation() multiple times * `_attestationData` is only passed to be emitted * @param _fisherman Creator of dispute * @param _deposit Amount of tokens staked as deposit * @param _attestation Attestation struct parsed from bytes * @param _attestationData Attestation bytes submitted by the fisherman * @return DisputeID */ function _createQueryDisputeWithAttestation( address _fisherman, uint256 _deposit, Attestation memory _attestation, bytes memory _attestationData ) private returns (bytes32) { // Get the indexer that signed the attestation address indexer = getAttestationIndexer(_attestation); // The indexer is disputable require(staking().hasStake(indexer), "Dispute indexer has no stake"); // Create a disputeID bytes32 disputeID = keccak256( abi.encodePacked( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID, indexer, _fisherman ) ); // Only one dispute for a (indexer, subgraphDeploymentID) at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Store dispute disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0 // no related dispute ); emit QueryDisputeCreated( disputeID, indexer, _fisherman, _deposit, _attestation.subgraphDeploymentID, _attestationData ); return disputeID; } /** * @dev Create an indexing dispute for the arbitrator to resolve. * The disputes are created in reference to an allocationID * This function is called by a challenger that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _allocationID The allocation to dispute * @param _deposit Amount of tokens staked as deposit */ function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createIndexingDisputeWithAllocation(msg.sender, _deposit, _allocationID); } /** * @dev Create indexing dispute internal function. * @param _fisherman The challenger creating the dispute * @param _deposit Amount of tokens staked as deposit * @param _allocationID Allocation disputed */ function _createIndexingDisputeWithAllocation( address _fisherman, uint256 _deposit, address _allocationID ) private returns (bytes32) { // Create a disputeID bytes32 disputeID = keccak256(abi.encodePacked(_allocationID)); // Only one dispute for an allocationID at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Allocation must exist IStaking.Allocation memory alloc = staking().getAllocation(_allocationID); require(alloc.indexer != address(0), "Dispute allocation must exist"); // The indexer must be disputable require(staking().hasStake(alloc.indexer), "Dispute indexer has no stake"); // Store dispute disputes[disputeID] = Dispute(alloc.indexer, _fisherman, _deposit, 0); emit IndexingDisputeCreated(disputeID, alloc.indexer, _fisherman, _deposit, _allocationID); return disputeID; } /** * @dev The arbitrator accepts a dispute as being valid. * @notice Accept a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be accepted */ function acceptDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Slash uint256 tokensToReward = _slashIndexer(dispute.indexer, dispute.fisherman); // Give the fisherman their deposit back if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeAccepted( _disputeID, dispute.indexer, dispute.fisherman, dispute.deposit.add(tokensToReward) ); } /** * @dev The arbitrator rejects a dispute as being invalid. * @notice Reject a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be rejected */ function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Handle conflicting dispute if any require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); // Burn the fisherman's deposit if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev The arbitrator draws dispute. * @notice Ignore a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be disregarded */ function drawDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Return deposit to the fisherman if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeDrawn(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev Resolve a dispute by removing it from storage and returning a memory copy. * @param _disputeID ID of the dispute to resolve * @return Dispute */ function _resolveDispute(bytes32 _disputeID) private returns (Dispute memory) { require(isDisputeCreated(_disputeID), "Dispute does not exist"); Dispute memory dispute = disputes[_disputeID]; // Resolve dispute delete disputes[_disputeID]; // Re-entrancy return dispute; } /** * @dev Returns whether the dispute is for a conflicting attestation or not. * @param _dispute Dispute * @return True conflicting attestation dispute */ function _isDisputeInConflict(Dispute memory _dispute) private pure returns (bool) { return _dispute.relatedDisputeID != 0; } /** * @dev Resolve the conflicting dispute if there is any for the one passed to this function. * @param _dispute Dispute * @return True if resolved */ function _resolveDisputeInConflict(Dispute memory _dispute) private returns (bool) { if (_isDisputeInConflict(_dispute)) { bytes32 relatedDisputeID = _dispute.relatedDisputeID; delete disputes[relatedDisputeID]; return true; } return false; } /** * @dev Pull deposit from submitter account. * @param _deposit Amount of tokens to deposit */ function _pullSubmitterDeposit(uint256 _deposit) private { // Ensure that fisherman has staked at least the minimum amount require(_deposit >= minimumDeposit, "Dispute deposit is under minimum required"); // Transfer tokens to deposit from fisherman to this contract require( graphToken().transferFrom(msg.sender, address(this), _deposit), "Cannot transfer tokens to deposit" ); } /** * @dev Make the staking contract slash the indexer and reward the challenger. * Give the challenger a reward equal to the fishermanRewardPercentage of slashed amount * @param _indexer Address of the indexer * @param _challenger Address of the challenger * @return Dispute reward tokens */ function _slashIndexer(address _indexer, address _challenger) private returns (uint256) { // Have staking contract slash the indexer and reward the fisherman // Give the fisherman a reward equal to the fishermanRewardPercentage of slashed amount uint256 tokensToSlash = getTokensToSlash(_indexer); uint256 tokensToReward = getTokensToReward(_indexer); require(tokensToSlash > 0, "Dispute has zero tokens to slash"); staking().slash(_indexer, tokensToSlash, tokensToReward, _challenger); return tokensToReward; } /** * @dev Recover the signer address of the `_attestation`. * @param _attestation The attestation struct * @return Signer address */ function _recoverAttestationSigner(Attestation memory _attestation) private view returns (address) { // Obtain the hash of the fully-encoded message, per EIP-712 encoding Receipt memory receipt = Receipt( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID ); bytes32 messageHash = encodeHashReceipt(receipt); // Obtain the signer of the fully-encoded EIP-712 message hash // NOTE: The signer of the attestation is the indexer that served the request return ECDSA.recover( messageHash, abi.encodePacked(_attestation.r, _attestation.s, _attestation.v) ); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Parse the bytes attestation into a struct from `_data`. * @return Attestation struct */ function _parseAttestation(bytes memory _data) private pure returns (Attestation memory) { // Check attestation data length require(_data.length == ATTESTATION_SIZE_BYTES, "Attestation must be 161 bytes long"); // Decode receipt (bytes32 requestCID, bytes32 responseCID, bytes32 subgraphDeploymentID) = abi.decode( _data, (bytes32, bytes32, bytes32) ); // Decode signature // Signature is expected to be in the order defined in the Attestation struct bytes32 r = _toBytes32(_data, SIG_R_OFFSET); bytes32 s = _toBytes32(_data, SIG_S_OFFSET); uint8 v = _toUint8(_data, SIG_V_OFFSET); return Attestation(requestCID, responseCID, subgraphDeploymentID, r, s, v); } /** * @dev Parse a uint8 from `_bytes` starting at offset `_start`. * @return uint8 value */ function _toUint8(bytes memory _bytes, uint256 _start) private pure returns (uint8) { require(_bytes.length >= (_start + UINT8_BYTE_LENGTH), "Bytes: out of bounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /** * @dev Parse a bytes32 from `_bytes` starting at offset `_start`. * @return bytes32 value */ function _toBytes32(bytes memory _bytes, uint256 _start) private pure returns (bytes32) { require(_bytes.length >= (_start + BYTES32_BYTE_LENGTH), "Bytes: out of bounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } }
* @dev Internal: Set the minimum deposit required to create a dispute. @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens @param _minimumDeposit The minimum deposit in Graph Tokens/
function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); }
908,948
[ 1, 3061, 30, 1000, 326, 5224, 443, 1724, 1931, 358, 752, 279, 1015, 2507, 18, 225, 2315, 326, 5224, 443, 1724, 358, 1375, 67, 15903, 758, 1724, 68, 5601, 13899, 225, 389, 15903, 758, 1724, 1021, 5224, 443, 1724, 316, 5601, 13899, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 13042, 758, 1724, 12, 11890, 5034, 389, 15903, 758, 1724, 13, 3238, 288, 203, 3639, 2583, 24899, 15903, 758, 1724, 405, 374, 16, 315, 13042, 443, 1724, 1297, 506, 444, 8863, 203, 3639, 5224, 758, 1724, 273, 389, 15903, 758, 1724, 31, 203, 3639, 3626, 5498, 7381, 2932, 15903, 758, 1724, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./interfaces/IConvexDeposit.sol"; import "./interfaces/IConvexWithdraw.sol"; import "./interfaces/ICurvePool.sol"; import "./interfaces/ICurvePool2.sol"; import "./interfaces/IUniswapV2Factory.sol"; import "./interfaces/IUniswapV2Router02.sol"; import "./interfaces/ITangoFactory.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/ISecretBridge.sol"; contract Constant { address public constant uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address public constant uniswapV2Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; address public constant ust = 0xa47c8bf37f92aBed4A126BDA807A7b7498661acD; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant curveBUSDPool = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB; address public constant curveUSTPool = 0x890f4e345B1dAED0367A877a1612f86A1f86985f; address public constant curveLpToken = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B; address public constant curveExchangeBUSD = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27; address public constant convexDeposit = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address public constant convexWithDrawAndClaim = 0x602c4cD53a715D8a7cf648540FAb0d3a2d546560; uint256 public constant pidBUSD = 3; } contract SecretStrategyBUSD is ITangoFactory, Constant, Ownable { using SafeERC20 for IERC20; uint256 public secretUST; uint256 public reserveUST; uint256 public minReserve; uint256 public stakedBalance; uint256 public depositFee; uint256 public rewardFee; uint256 public totalDepositFee; uint256 public totalRewardFee; uint256 public totalUSTDeposited; address public router; bytes public receiver; mapping(address => bool) isOperator; modifier onlyRouter() { require(msg.sender == router,"Only-router"); _; } modifier onlyOperator() { require(isOperator[msg.sender], "Only-operator"); _; } event Invest(address _user, uint256 _amount); event Withdraw(address _user, uint256 _amount); event Balance(uint256 _secretUST, uint256 _reserveUST); constructor(address _router, uint256 _minReserve) Ownable() { router = _router; minReserve = _minReserve; isOperator[msg.sender] = true; IERC20(curveLpToken).safeApprove(curveBUSDPool, type(uint256).max); IERC20(curveLpToken).safeApprove(convexDeposit, type(uint256).max); IERC20(usdc).safeApprove(curveUSTPool, type(uint256).max); IERC20(dai).safeApprove(curveUSTPool, type(uint256).max); IERC20(ust).safeApprove(curveUSTPool, type(uint256).max); IERC20(usdc).safeApprove(curveBUSDPool, type(uint256).max); IERC20(dai).safeApprove(curveBUSDPool, type(uint256).max); transferOwnership(0xfc0962770A2A1d142f7b48cb40d04001c73Af840); } function adminSetFee(uint256 _depositFee, uint256 _rewardFee) external onlyOwner() { depositFee = _depositFee; rewardFee = _rewardFee; } function adminSetMinReversed(uint256 _minReserve) external onlyOwner() { minReserve = _minReserve; } function adminSetRewardRecipient(bytes memory _receiver) external onlyOwner() { receiver = _receiver; } function adminWhiteListOperator(address _operator, bool _whitelist) external onlyOwner() { isOperator[_operator] = _whitelist; } function adminCollectFee(address _to) external onlyOwner() { IERC20(ust).safeTransfer(_to, totalDepositFee); IERC20(wETH).safeTransfer(_to, totalRewardFee); totalDepositFee = 0; totalRewardFee = 0; } function adminFillReserve(uint256 _amount) external onlyOwner() { IERC20(ust).safeTransferFrom(msg.sender, address(this), _amount); reserveUST = _amount; } function adminWithdrawToken(address _token, address _to, uint256 _amount) external onlyOwner() { IERC20(_token).safeTransfer(_to, _amount); } /** * @dev swap token at UniswapV2Router with path fromToken - WETH - toToken * @param _fromToken is source token * @param _toToken is des token * @param _swapAmount is amount of source token to swap * @return _amountOut is the amount of _toToken */ function _uniswapSwapToken( address _router, address _fromToken, address _toToken, uint256 _swapAmount ) private returns (uint256 _amountOut) { if(IERC20(_fromToken).allowance(address(this), _router) == 0) { IERC20(_fromToken).safeApprove(_router, type(uint256).max); } address[] memory path; if(_fromToken == wETH || _toToken == wETH) { path = new address[](2); path[0] = _fromToken == wETH ? wETH : _fromToken; path[1] = _toToken == wETH ? wETH : _toToken; } else { path = new address[](3); path[0] = _fromToken; path[1] = wETH; path[2] = _toToken; } _amountOut = IUniswapV2Router02(_router) .swapExactTokensForTokens( _swapAmount, 0, path, address(this), deadline )[path.length - 1]; } /** * @dev add liquidity to Curve at UST poool * @param _curvePool is curve liqudity pool address * @param _param is [ust, dai, usdc, usdt] * @return amount of lp token */ function _curveAddLiquidity(address _curvePool, uint256[4] memory _param) private returns(uint256) { return ICurvePool(_curvePool).add_liquidity(_param, 0); } /** * @dev add liquidity to Curve at UST poool * @param _curvePool is curve liqudity pool address * @param _curveLpBalance is amount lp token * @param i is index of toke * @return amount of lp token */ function _curveRemoveLiquidity(address _curvePool, uint256 _curveLpBalance, int128 i) private returns(uint256) { return ICurvePool(_curvePool).remove_liquidity_one_coin(_curveLpBalance, i, 0); } function calculateLpAmount(address _curvePool, uint256 _daiAmount) private returns (uint256){ return ICurvePool(_curvePool).calc_token_amount([_daiAmount, 0, 0, 0], false); } function exchangeUnderlying(address _curvePool, uint256 _dx, int128 i, int128 j) private returns (uint256) { return ICurvePool(_curvePool).exchange_underlying(i, j, _dx, 0); } function secretInvest(address _user, address _token, uint256 _amount) external override onlyRouter() { uint256 depositAmount = _amount; if(depositFee > 0) { uint256 fee = depositAmount * depositFee / 10000; depositAmount = depositAmount - fee; totalDepositFee = totalDepositFee + fee; } secretUST = secretUST + depositAmount; totalUSTDeposited = totalUSTDeposited + _amount; emit Invest(_user, _amount); } function withrawFromPool(uint256 _amount) private returns(uint256) { uint256 lpAmount = calculateLpAmount(curveExchangeBUSD ,_amount) * 101 / 100; // extra 1% _withdraw(convexWithDrawAndClaim, lpAmount); uint256 balanceUSDC = IERC20(usdc).balanceOf(address(this)); ICurvePool2(curveBUSDPool).remove_liquidity_one_coin(lpAmount, 1, 0); uint256 swapBalance = IERC20(usdc).balanceOf(address(this)) - balanceUSDC; uint256 balanceUST = exchangeUnderlying(curveUSTPool, swapBalance, 2, 0); return balanceUST; } function operatorRebalanceReserve() external onlyOperator() { require(reserveUST < minReserve, "No-need-rebalance-now"); uint256 _amount = minReserve - reserveUST; reserveUST = reserveUST + withrawFromPool(_amount); require(IERC20(ust).balanceOf(address(this)) >= reserveUST, "Something-went-wrong"); } function secretWithdraw(address _user, uint256 _amount) external override onlyRouter() { emit Withdraw(_user, _amount); if (secretUST >= _amount) { IERC20(ust).safeTransfer(_user, _amount); secretUST = secretUST - _amount; emit Balance(secretUST, reserveUST); return; } else if(secretUST + reserveUST >= _amount) { reserveUST = reserveUST + secretUST - _amount; secretUST = 0; IERC20(ust).safeTransfer(_user, _amount); emit Balance(secretUST, reserveUST); return; } else if (reserveUST >= _amount) { IERC20(ust).safeTransfer(_user, _amount); reserveUST = reserveUST - _amount; emit Balance(secretUST, reserveUST); return; } else { uint256 balanceUST = withrawFromPool(_amount); require(balanceUST >= _amount); IERC20(ust).safeTransfer(_user, _amount); if(balanceUST > _amount) { reserveUST = reserveUST + balanceUST - _amount; } } } function operatorClaimRewardsToSCRT(address _secretBridge) external override onlyOperator() { uint256 wETHBalanceBefore = IERC20(wETH).balanceOf(address(this)); uint256 balanceCRV = IERC20(crv).balanceOf(address(this)); uint256 balanceCVX = IERC20(cvx).balanceOf(address(this)); IConvexWithdraw(convexWithDrawAndClaim).getReward(); uint256 amountCRV = IERC20(crv).balanceOf(address(this)) - balanceCRV; uint256 amountCVX = IERC20(cvx).balanceOf(address(this)) - balanceCVX; if(amountCRV > 0) { _uniswapSwapToken(uniRouter, crv, wETH, amountCRV); } if(amountCVX > 0) { _uniswapSwapToken(sushiRouter, cvx, wETH, amountCVX); } uint256 wETHBalanceAfter = IERC20(wETH).balanceOf(address(this)); uint256 balanceDiff = wETHBalanceAfter - wETHBalanceBefore; if(rewardFee > 0) { uint256 fee = balanceDiff * rewardFee / 10000; balanceDiff = balanceDiff - fee; totalRewardFee = totalRewardFee + fee; } IWETH(wETH).withdraw(balanceDiff); ISecretBridge(_secretBridge).swap{value: balanceDiff}(receiver); } function operatorInvest() external onlyOperator() { uint256 amountUSDC = exchangeUnderlying(curveUSTPool, secretUST, 0, 2); uint256 balanceLP = IERC20(curveLpToken).balanceOf(address(this)); ICurvePool2(curveBUSDPool).add_liquidity([0, amountUSDC, 0, 0], 0); uint256 balanceDiff = IERC20(curveLpToken).balanceOf(address(this)) - balanceLP; require(balanceDiff > 0, "Invalid-balance"); _stake(convexDeposit, pidBUSD, balanceDiff); secretUST = 0; } function _stake(address _pool, uint256 _pid, uint256 _stakeAmount) private { IConvexDeposit(_pool).depositAll(_pid, true); stakedBalance = stakedBalance + _stakeAmount; } function _withdraw(address _pool, uint256 _amount) private { IConvexWithdraw(_pool).withdrawAndUnwrap(_amount, false); stakedBalance = stakedBalance - _amount; } function getStakingInfor() public view returns(uint256, uint256) { uint256 currentStakedBalance = IConvexWithdraw(convexWithDrawAndClaim).balanceOf(address(this)); uint256 rewardBalance = IConvexWithdraw(convexWithDrawAndClaim).earned(address(this)); return (currentStakedBalance, rewardBalance); } receive() external payable { } } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.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 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' 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 { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT 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 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. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConvexDeposit{ function depositAll(uint256 _pid, bool _stake) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConvexWithdraw{ function withdrawAndUnwrap(uint256, bool) external; function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getReward() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICurvePool { function add_liquidity(uint256[4] memory, uint256) external returns(uint256); function remove_liquidity_one_coin(uint256, int128, uint256) external returns(uint256); function calc_token_amount(uint256[4] memory, bool) external returns(uint256); function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICurvePool2 { function add_liquidity(uint256[4] memory, uint256) external; function remove_liquidity_one_coin(uint256, int128, uint256) external; function remove_liquidity_imbalance(uint256[4] memory, uint256) external; function get_virtual_price() external returns (uint256); function calc_token_amount(uint256[4] memory, bool) external returns(uint256); function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); 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); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITangoFactory { function secretInvest(address, address, uint256) external; function secretWithdraw(address , uint256) external; function operatorClaimRewardsToSCRT(address) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ISecretBridge { function swap(bytes memory _recipient) external payable; } // SPDX-License-Identifier: MIT 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 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @dev add liquidity to Curve at UST poool @param _curvePool is curve liqudity pool address @param _curveLpBalance is amount lp token @param i is index of toke @return amount of lp token/
function _curveRemoveLiquidity(address _curvePool, uint256 _curveLpBalance, int128 i) private returns(uint256) { return ICurvePool(_curvePool).remove_liquidity_one_coin(_curveLpBalance, i, 0); }
1,148,639
[ 1, 1289, 4501, 372, 24237, 358, 22901, 622, 587, 882, 8275, 1371, 225, 389, 16683, 2864, 353, 8882, 4501, 372, 72, 560, 2845, 1758, 225, 389, 16683, 48, 84, 13937, 353, 3844, 12423, 1147, 225, 277, 353, 770, 434, 946, 73, 327, 3844, 434, 12423, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 16683, 3288, 48, 18988, 24237, 12, 2867, 389, 16683, 2864, 16, 2254, 5034, 389, 16683, 48, 84, 13937, 16, 509, 10392, 277, 13, 3238, 1135, 12, 11890, 5034, 13, 288, 7010, 3639, 327, 467, 9423, 2864, 24899, 16683, 2864, 2934, 4479, 67, 549, 372, 24237, 67, 476, 67, 12645, 24899, 16683, 48, 84, 13937, 16, 277, 16, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 {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. */ 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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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); } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.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 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' 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 { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * 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 AccessControlUpgradeable is Initializable, IAccessControl { function __AccessControl_init() internal initializer { __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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 {_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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, msg.sender); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.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 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) external 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) external 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 granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == msg.sender, "71"); _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 { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface IAngleMiddlemanGauge { function notifyReward(address gauge, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface IGaugeController { //solhint-disable-next-line function gauge_types(address addr) external view returns (int128); //solhint-disable-next-line function gauge_relative_weight_write(address addr, uint256 timestamp) external returns (uint256); //solhint-disable-next-line function gauge_relative_weight(address addr, uint256 timestamp) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface ILiquidityGauge { // solhint-disable-next-line function deposit_reward_token(address _rewardToken, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IStakingRewardsFunctions /// @author Angle Core Team /// @notice Interface for the staking rewards contract that interact with the `RewardsDistributor` contract interface IStakingRewardsFunctions { function notifyRewardAmount(uint256 reward) external; function recoverERC20( address tokenAddress, address to, uint256 tokenAmount ) external; function setNewRewardsDistribution(address newRewardsDistribution) external; } /// @title IStakingRewards /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IStakingRewards is IStakingRewardsFunctions { function rewardToken() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "./AngleDistributorEvents.sol"; /// @title AngleDistributor /// @author Forked from contracts developed by Curve and Frax and adapted by Angle Core Team /// - ERC20CRV.vy (https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/ERC20CRV.vy) /// - FraxGaugeFXSRewardsDistributor.sol (https://github.com/FraxFinance/frax-solidity/blob/master/src/hardhat/contracts/Curve/FraxGaugeFXSRewardsDistributor.sol) /// @notice All the events used in `AngleDistributor` contract contract AngleDistributor is AngleDistributorEvents, ReentrancyGuardUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20; /// @notice Role for governors only bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE"); /// @notice Role for the guardian bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); /// @notice Length of a week in seconds uint256 public constant WEEK = 3600 * 24 * 7; /// @notice Time at which the emission rate is updated uint256 public constant RATE_REDUCTION_TIME = WEEK; /// @notice Reduction of the emission rate uint256 public constant RATE_REDUCTION_COEFFICIENT = 1007827884862117171; // 1.5 ^ (1/52) * 10**18 /// @notice Base used for computation uint256 public constant BASE = 10**18; /// @notice Maps the address of a gauge to the last time this gauge received rewards mapping(address => uint256) public lastTimeGaugePaid; /// @notice Maps the address of a gauge to whether it was killed or not /// A gauge killed in this contract cannot receive any rewards mapping(address => bool) public killedGauges; /// @notice Maps the address of a type >= 2 gauge to a delegate address responsible /// for giving rewards to the actual gauge mapping(address => address) public delegateGauges; /// @notice Maps the address of a gauge delegate to whether this delegate supports the `notifyReward` interface /// and is therefore built for automation mapping(address => bool) public isInterfaceKnown; /// @notice Address of the ANGLE token given as a reward IERC20 public rewardToken; /// @notice Address of the `GaugeController` contract IGaugeController public controller; /// @notice Address responsible for pulling rewards of type >= 2 gauges and distributing it to the /// associated contracts if there is not already an address delegated for this specific contract address public delegateGauge; /// @notice ANGLE current emission rate, it is first defined in the initializer and then updated every week uint256 public rate; /// @notice Timestamp at which the current emission epoch started uint256 public startEpochTime; /// @notice Amount of ANGLE tokens distributed through staking at the start of the epoch /// This is an informational variable used to track how much has been distributed through liquidity mining uint256 public startEpochSupply; /// @notice Index of the current emission epoch /// Here also, this variable is not useful per se inside the smart contracts of the protocol, it is /// just an informational variable uint256 public miningEpoch; /// @notice Whether ANGLE distribution through this contract is on or no bool public distributionsOn; /// @notice Constructor of the contract /// @param _rewardToken Address of the ANGLE token /// @param _controller Address of the GaugeController /// @param _initialRate Initial ANGLE emission rate /// @param _startEpochSupply Amount of ANGLE tokens already distributed via liquidity mining /// @param governor Governor address of the contract /// @param guardian Address of the guardian of this contract /// @param _delegateGauge Address that will be used to pull rewards for type 2 gauges /// @dev After this contract is created, the correct amount of ANGLE tokens should be transferred to the contract /// @dev The `_delegateGauge` can be the zero address function initialize( address _rewardToken, address _controller, uint256 _initialRate, uint256 _startEpochSupply, address governor, address guardian, address _delegateGauge ) external initializer { require( _controller != address(0) && _rewardToken != address(0) && guardian != address(0) && governor != address(0), "0" ); rewardToken = IERC20(_rewardToken); controller = IGaugeController(_controller); startEpochSupply = _startEpochSupply; miningEpoch = 0; // Some ANGLE tokens should be sent to the contract directly after initialization rate = _initialRate; delegateGauge = _delegateGauge; distributionsOn = false; startEpochTime = block.timestamp; _setRoleAdmin(GOVERNOR_ROLE, GOVERNOR_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERNOR_ROLE); _setupRole(GUARDIAN_ROLE, guardian); _setupRole(GOVERNOR_ROLE, governor); _setupRole(GUARDIAN_ROLE, governor); } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // ======================== Internal Functions ================================= /// @notice Internal function to distribute rewards to a gauge /// @param gaugeAddr Address of the gauge to distribute rewards to /// @return weeksElapsed Weeks elapsed since the last call /// @return rewardTally Amount of rewards distributed to the gauge /// @dev The reason for having an internal function is that it's called by the `distributeReward` and the /// `distributeRewardToMultipleGauges` /// @dev Although they would need to be performed all the time this function is called, this function does not /// contain checks on whether distribution is on, and on whether rate should be reduced. These are done in each external /// function calling this function for gas efficiency function _distributeReward(address gaugeAddr) internal returns (uint256 weeksElapsed, uint256 rewardTally) { // Checking if the gauge has been added or if it still possible to distribute rewards to this gauge int128 gaugeType = IGaugeController(controller).gauge_types(gaugeAddr); require(gaugeType >= 0 && !killedGauges[gaugeAddr], "110"); // Calculate the elapsed time in weeks. uint256 lastTimePaid = lastTimeGaugePaid[gaugeAddr]; // Edge case for first reward for this gauge if (lastTimePaid == 0) { weeksElapsed = 1; if (gaugeType == 0) { // We give a full approval for the gauges with type zero which correspond to the staking // contracts of the protocol rewardToken.safeApprove(gaugeAddr, type(uint256).max); } } else { // Truncation desired weeksElapsed = (block.timestamp - lastTimePaid) / WEEK; // Return early here for 0 weeks instead of throwing, as it could have bad effects in other contracts if (weeksElapsed == 0) { return (0, 0); } } rewardTally = 0; // We use this variable to keep track of the emission rate across different weeks uint256 weeklyRate = rate; for (uint256 i = 0; i < weeksElapsed; i++) { uint256 relWeightAtWeek; if (i == 0) { // Mutative, for the current week: makes sure the weight is checkpointed. Also returns the weight. relWeightAtWeek = controller.gauge_relative_weight_write(gaugeAddr, block.timestamp); } else { // View relWeightAtWeek = controller.gauge_relative_weight(gaugeAddr, (block.timestamp - WEEK * i)); } rewardTally += (weeklyRate * relWeightAtWeek * WEEK) / BASE; // To get the rate of the week prior from the current rate we just have to multiply by the weekly division // factor // There may be some precisions error: inferred previous values of the rate may be different to what we would // have had if the rate had been computed correctly in these weeks: we expect from empirical observations // this `weeklyRate` to be inferior to what the `rate` would have been weeklyRate = (weeklyRate * RATE_REDUCTION_COEFFICIENT) / BASE; } // Update the last time paid, rounded to the closest week // in order not to have an ever moving time on when to call this function lastTimeGaugePaid[gaugeAddr] = (block.timestamp / WEEK) * WEEK; // If the `gaugeType >= 2`, this means that the gauge is a gauge on another chain (and corresponds to tokens // that need to be bridged) or is associated to an external contract of the Angle Protocol if (gaugeType >= 2) { // If it is defined, we use the specific delegate attached to the gauge address delegate = delegateGauges[gaugeAddr]; if (delegate == address(0)) { // If not, we check if a delegate common to all gauges with type >= 2 can be used delegate = delegateGauge; } if (delegate != address(0)) { // In the case where the gauge has a delegate (specific or not), then rewards are transferred to this gauge rewardToken.safeTransfer(delegate, rewardTally); // If this delegate supports a specific interface, then rewards sent are notified through this // interface if (isInterfaceKnown[delegate]) { IAngleMiddlemanGauge(delegate).notifyReward(gaugeAddr, rewardTally); } } else { rewardToken.safeTransfer(gaugeAddr, rewardTally); } } else if (gaugeType == 1) { // This is for the case of Perpetual contracts which need to be able to receive their reward tokens rewardToken.safeTransfer(gaugeAddr, rewardTally); IStakingRewards(gaugeAddr).notifyRewardAmount(rewardTally); } else { // Mainnet: Pay out the rewards directly to the gauge ILiquidityGauge(gaugeAddr).deposit_reward_token(address(rewardToken), rewardTally); } emit RewardDistributed(gaugeAddr, rewardTally); } /// @notice Updates mining rate and supply at the start of the epoch /// @dev Any modifying mining call must also call this /// @dev It is possible that more than one week past between two calls of this function, and for this reason /// this function has been slightly modified from Curve implementation by Angle Team function _updateMiningParameters() internal { // When entering this function, we always have: `(block.timestamp - startEpochTime) / RATE_REDUCTION_TIME >= 1` uint256 epochDelta = (block.timestamp - startEpochTime) / RATE_REDUCTION_TIME; // Storing intermediate values for the rate and for the `startEpochSupply` uint256 _rate = rate; uint256 _startEpochSupply = startEpochSupply; startEpochTime += RATE_REDUCTION_TIME * epochDelta; miningEpoch += epochDelta; for (uint256 i = 0; i < epochDelta; i++) { // Updating the intermediate values of the `startEpochSupply` _startEpochSupply += _rate * RATE_REDUCTION_TIME; _rate = (_rate * BASE) / RATE_REDUCTION_COEFFICIENT; } rate = _rate; startEpochSupply = _startEpochSupply; emit UpdateMiningParameters(block.timestamp, _rate, _startEpochSupply); } /// @notice Toggles the fact that a gauge delegate can be used for automation or not and therefore supports /// the `notifyReward` interface /// @param _delegateGauge Address of the gauge to change function _toggleInterfaceKnown(address _delegateGauge) internal { bool isInterfaceKnownMem = isInterfaceKnown[_delegateGauge]; isInterfaceKnown[_delegateGauge] = !isInterfaceKnownMem; emit InterfaceKnownToggled(_delegateGauge, !isInterfaceKnownMem); } // ================= Permissionless External Functions ========================= /// @notice Distributes rewards to a staking contract (also called gauge) /// @param gaugeAddr Address of the gauge to send tokens too /// @return weeksElapsed Number of weeks elapsed since the last time rewards were distributed /// @return rewardTally Amount of tokens sent to the gauge /// @dev Anyone can call this function to distribute rewards to the different staking contracts function distributeReward(address gaugeAddr) external nonReentrant returns (uint256, uint256) { // Checking if distribution is on require(distributionsOn == true, "109"); // Updating rate distribution parameters if need be if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) { _updateMiningParameters(); } return _distributeReward(gaugeAddr); } /// @notice Distributes rewards to multiple staking contracts /// @param gauges Addresses of the gauge to send tokens too /// @dev Anyone can call this function to distribute rewards to the different staking contracts /// @dev Compared with the `distributeReward` function, this function sends rewards to multiple /// contracts at the same time function distributeRewardToMultipleGauges(address[] memory gauges) external nonReentrant { // Checking if distribution is on require(distributionsOn == true, "109"); // Updating rate distribution parameters if need be if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) { _updateMiningParameters(); } for (uint256 i = 0; i < gauges.length; i++) { _distributeReward(gauges[i]); } } /// @notice Updates mining rate and supply at the start of the epoch /// @dev Callable by any address, but only once per epoch function updateMiningParameters() external { require(block.timestamp >= startEpochTime + RATE_REDUCTION_TIME, "108"); _updateMiningParameters(); } // ========================= Governor Functions ================================ /// @notice Withdraws ERC20 tokens that could accrue on this contract /// @param tokenAddress Address of the ERC20 token to withdraw /// @param to Address to transfer to /// @param amount Amount to transfer /// @dev Added to support recovering LP Rewards and other mistaken tokens /// from other systems to be distributed to holders /// @dev This function could also be used to recover ANGLE tokens in case the rate got smaller function recoverERC20( address tokenAddress, address to, uint256 amount ) external onlyRole(GOVERNOR_ROLE) { // If the token is the ANGLE token, we need to make sure that governance is not going to withdraw // too many tokens and that it'll be able to sustain the weekly distribution forever // This check assumes that `distributeReward` has been called for gauges and that there are no gauges // which have not received their past week's rewards if (tokenAddress == address(rewardToken)) { uint256 currentBalance = rewardToken.balanceOf(address(this)); // The amount distributed till the end is `rate * WEEK / (1 - RATE_REDUCTION_FACTOR)` where // `RATE_REDUCTION_FACTOR = BASE / RATE_REDUCTION_COEFFICIENT` which translates to: require( currentBalance >= ((rate * RATE_REDUCTION_COEFFICIENT) * WEEK) / (RATE_REDUCTION_COEFFICIENT - BASE) + amount, "4" ); } IERC20(tokenAddress).safeTransfer(to, amount); emit Recovered(tokenAddress, to, amount); } /// @notice Sets a new gauge controller /// @param _controller Address of the new gauge controller function setGaugeController(address _controller) external onlyRole(GOVERNOR_ROLE) { require(_controller != address(0), "0"); controller = IGaugeController(_controller); emit GaugeControllerUpdated(_controller); } /// @notice Sets a new delegate gauge for pulling rewards of a type >= 2 gauges or of all type >= 2 gauges /// @param gaugeAddr Gauge to change the delegate of /// @param _delegateGauge Address of the new gauge delegate related to `gaugeAddr` /// @param toggleInterface Whether we should toggle the fact that the `_delegateGauge` is built for automation or not /// @dev This function can be used to remove delegating or introduce the pulling of rewards to a given address /// @dev If `gaugeAddr` is the zero address, this function updates the delegate gauge common to all gauges with type >= 2 /// @dev The `toggleInterface` parameter has been added for convenience to save one transaction when adding a gauge delegate /// which supports the `notifyReward` interface function setDelegateGauge( address gaugeAddr, address _delegateGauge, bool toggleInterface ) external onlyRole(GOVERNOR_ROLE) { if (gaugeAddr != address(0)) { delegateGauges[gaugeAddr] = _delegateGauge; } else { delegateGauge = _delegateGauge; } emit DelegateGaugeUpdated(gaugeAddr, _delegateGauge); if (toggleInterface) { _toggleInterfaceKnown(_delegateGauge); } } /// @notice Changes the ANGLE emission rate /// @param _newRate New ANGLE emission rate /// @dev It is important to be super wary when calling this function and to make sure that `distributeReward` /// has been called for all gauges in the past weeks. If not, gauges may get an incorrect distribution of ANGLE rewards /// for these past weeks based on the new rate and not on the old rate /// @dev Governance should thus make sure to call this function rarely and when it does to do it after the weekly `distributeReward` /// calls for all existing gauges /// @dev As this function assumes that `distributeReward` has been called during the week, it also assumes that the `startEpochSupply` /// parameter has been put up to date function setRate(uint256 _newRate) external onlyRole(GOVERNOR_ROLE) { // Checking if the new rate is compatible with the amount of ANGLE tokens this contract has in balance // This check assumes, like this function, that `distributeReward` has correctly been called before require( rewardToken.balanceOf(address(this)) >= ((_newRate * RATE_REDUCTION_COEFFICIENT) * WEEK) / (RATE_REDUCTION_COEFFICIENT - BASE), "4" ); rate = _newRate; emit RateUpdated(_newRate); } /// @notice Toggles the status of a gauge to either killed or unkilled /// @param gaugeAddr Gauge to toggle the status of /// @dev It is impossible to kill a gauge in the `GaugeController` contract, for this reason killing of gauges /// takes place in the `AngleDistributor` contract /// @dev This means that people could vote for a gauge in the gauge controller contract but that rewards are not going /// to be distributed to it in the end: people would need to remove their weights on the gauge killed to end the diminution /// in rewards /// @dev In the case of a gauge being killed, this function resets the timestamps at which this gauge has been approved and /// disapproves the gauge to spend the token /// @dev It should be cautiously called by governance as it could result in less ANGLE overall rewards than initially planned /// if people do not remove their voting weights to the killed gauge function toggleGauge(address gaugeAddr) external onlyRole(GOVERNOR_ROLE) { bool gaugeKilledMem = killedGauges[gaugeAddr]; if (!gaugeKilledMem) { delete lastTimeGaugePaid[gaugeAddr]; rewardToken.safeApprove(gaugeAddr, 0); } killedGauges[gaugeAddr] = !gaugeKilledMem; emit GaugeToggled(gaugeAddr, !gaugeKilledMem); } // ========================= Guardian Function ================================= /// @notice Halts or activates distribution of rewards function toggleDistributions() external onlyRole(GUARDIAN_ROLE) { bool distributionsOnMem = distributionsOn; distributionsOn = !distributionsOnMem; emit DistributionsToggled(!distributionsOnMem); } /// @notice Notifies that the interface of a gauge delegate is known or has changed /// @param _delegateGauge Address of the gauge to change /// @dev Gauge delegates that are built for automation should be toggled function toggleInterfaceKnown(address _delegateGauge) external onlyRole(GUARDIAN_ROLE) { _toggleInterfaceKnown(_delegateGauge); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../interfaces/IGaugeController.sol"; import "../interfaces/ILiquidityGauge.sol"; import "../interfaces/IAngleMiddlemanGauge.sol"; import "../interfaces/IStakingRewards.sol"; import "../external/AccessControlUpgradeable.sol"; /// @title AngleDistributorEvents /// @author Angle Core Team /// @notice All the events used in `AngleDistributor` contract contract AngleDistributorEvents { event DelegateGaugeUpdated(address indexed _gaugeAddr, address indexed _delegateGauge); event DistributionsToggled(bool _distributionsOn); event GaugeControllerUpdated(address indexed _controller); event GaugeToggled(address indexed gaugeAddr, bool newStatus); event InterfaceKnownToggled(address indexed _delegateGauge, bool _isInterfaceKnown); event RateUpdated(uint256 _newRate); event Recovered(address indexed tokenAddress, address indexed to, uint256 amount); event RewardDistributed(address indexed gaugeAddr, uint256 rewardTally); event UpdateMiningParameters(uint256 time, uint256 rate, uint256 supply); }
@title AngleDistributorEvents @author Angle Core Team @notice All the events used in `AngleDistributor` contract
contract AngleDistributorEvents { event DelegateGaugeUpdated(address indexed _gaugeAddr, address indexed _delegateGauge); event DistributionsToggled(bool _distributionsOn); event GaugeControllerUpdated(address indexed _controller); event GaugeToggled(address indexed gaugeAddr, bool newStatus); event InterfaceKnownToggled(address indexed _delegateGauge, bool _isInterfaceKnown); event RateUpdated(uint256 _newRate); event Recovered(address indexed tokenAddress, address indexed to, uint256 amount); event RewardDistributed(address indexed gaugeAddr, uint256 rewardTally); event UpdateMiningParameters(uint256 time, uint256 rate, uint256 supply); }
5,933,751
[ 1, 8467, 1669, 19293, 3783, 225, 24154, 4586, 10434, 225, 4826, 326, 2641, 1399, 316, 1375, 8467, 1669, 19293, 68, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 24154, 1669, 19293, 3783, 288, 203, 565, 871, 27687, 18941, 7381, 12, 2867, 8808, 389, 75, 8305, 3178, 16, 1758, 8808, 389, 22216, 18941, 1769, 203, 565, 871, 3035, 15326, 56, 23972, 1259, 12, 6430, 389, 2251, 15326, 1398, 1769, 203, 565, 871, 19766, 2933, 7381, 12, 2867, 8808, 389, 5723, 1769, 203, 565, 871, 19766, 56, 23972, 1259, 12, 2867, 8808, 13335, 3178, 16, 1426, 394, 1482, 1769, 203, 565, 871, 6682, 11925, 56, 23972, 1259, 12, 2867, 8808, 389, 22216, 18941, 16, 1426, 389, 291, 1358, 11925, 1769, 203, 565, 871, 13025, 7381, 12, 11890, 5034, 389, 2704, 4727, 1769, 203, 565, 871, 868, 16810, 12, 2867, 8808, 1147, 1887, 16, 1758, 8808, 358, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 534, 359, 1060, 1669, 11050, 12, 2867, 8808, 13335, 3178, 16, 2254, 5034, 19890, 56, 1230, 1769, 203, 565, 871, 2315, 2930, 310, 2402, 12, 11890, 5034, 813, 16, 2254, 5034, 4993, 16, 2254, 5034, 14467, 1769, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xf8B127481e60c36465c04aF489e27567c9a3014D/sources/EXAToken.sol
------------------------------------------------------------------------ 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 returns (bool success) { require(to != address(0)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
9,275,814
[ 1, 29461, 12279, 326, 11013, 628, 1147, 3410, 1807, 2236, 358, 1375, 869, 68, 2236, 300, 16837, 1807, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /* m_1 - 21401 m_2 - 21401 m_3 - 21341 m_4 - 26231 m_5 - 26244 m_6 - 26445 m_7 - 26231 m_8 - 26244 m_9 - 26416 */ // uint8 storage and setter contract MathOperators_1 { function Operator_1() public { uint256 a = 1; a = a + 1; } } contract MathOperators_2 { function Operator_1() public { uint256 a = 1; a += 1; } } contract MathOperators_3 { function Operator_1() public { uint256 a = 1; a ++; } } contract MathOperators_4 { uint256 public a = 5; function Operator_1() public { a = a<<2; } } contract MathOperators_5 { uint256 public a = 5; function Operator_1() public { a <<=2; } } contract MathOperators_6 { uint256 public a = 5; function Operator_1() public { a *= 2**2; } } contract MathOperators_7 { uint256 public a = 21000000; function Operator_1() public { a = a>>10; } } contract MathOperators_8 { uint256 public a = 21000000; function Operator_1() public { a >>=10; } } contract MathOperators_9 { uint256 public a = 21000000; function Operator_1() public { a /= 2**10; } }
uint8 storage and setter
contract MathOperators_1 { pragma solidity 0.8.9; m_1 - 21401 function Operator_1() public { uint256 a = 1; a = a + 1; } }
2,507,144
[ 1, 11890, 28, 2502, 471, 7794, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2361, 24473, 67, 21, 288, 203, 1377, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 29, 31, 203, 81, 67, 21, 300, 30149, 1611, 21281, 203, 377, 445, 11097, 67, 21, 1435, 1071, 288, 203, 4202, 2254, 5034, 279, 273, 404, 31, 203, 4202, 279, 273, 279, 397, 404, 31, 203, 377, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.0; //pragma experimental ABIEncoderV2; import './Utils.sol'; import './Verifier.sol'; import './MerkleTree_Stateless.sol'; import './Structures.sol'; library ChallengesUtil { bytes32 public constant ZERO = 0x0000000000000000000000000000000000000000000000000000000000000000; function libChallengeLeafCountCorrect( Structures.Block memory priorBlockL2, Structures.Transaction[] memory priorBlockTransactions, uint256 leafCount ) public pure { uint256 expectedLeafCount = priorBlockL2.leafCount + Utils.countCommitments(priorBlockTransactions); require(expectedLeafCount != leafCount, 'The leafCount is actually correct'); } function libChallengeNewRootCorrect( Structures.Block memory priorBlockL2, // the block immediately prior to this one Structures.Transaction[] memory priorBlockTransactions, // the transactions in the prior block bytes32[33] calldata frontierPriorBlock, // frontier path before prior block is added. The same frontier used in calculating root when prior block is added Structures.Block memory blockL2, Structures.Transaction[] memory transactions ) public pure { // next check the sibling path is valid and get the Frontier bool valid; bytes32[33] memory _frontier; (valid, _frontier) = MerkleTree_Stateless.checkPath( Utils.filterCommitments(priorBlockTransactions), frontierPriorBlock, priorBlockL2.leafCount, priorBlockL2.root ); require(valid, 'The sibling path is invalid'); uint256 commitmentIndex = priorBlockL2.leafCount + Utils.filterCommitments(priorBlockTransactions).length; // At last, we can check if the root itself is correct! (bytes32 root, , ) = MerkleTree_Stateless.insertLeaves( Utils.filterCommitments(transactions), _frontier, commitmentIndex ); require(root != blockL2.root, 'The root is actually fine'); } // the transaction type is challenged to not be valid function libChallengeTransactionType(Structures.Transaction memory transaction) public pure { if (transaction.transactionType == Structures.TransactionTypes.DEPOSIT) libChallengeTransactionTypeDeposit(transaction); // TODO add these checks back after PR for out of gas else if (transaction.transactionType == Structures.TransactionTypes.SINGLE_TRANSFER) libChallengeTransactionTypeSingleTransfer(transaction); else if (transaction.transactionType == Structures.TransactionTypes.DOUBLE_TRANSFER) libChallengeTransactionTypeDoubleTransfer(transaction); // if(transaction.transactionType == TransactionTypes.WITHDRAW) else libChallengeTransactionTypeWithdraw(transaction); } // the transaction type deposit is challenged to not be valid function libChallengeTransactionTypeDeposit(Structures.Transaction memory transaction) public pure { uint256 nZeroProof; for (uint256 i = 0; i < transaction.proof.length; i++) { if (transaction.proof[i] == 0) nZeroProof++; } require( (transaction.tokenId == ZERO && transaction.value == 0) || transaction.ercAddress == ZERO || transaction.recipientAddress != ZERO || transaction.commitments[0] == ZERO || transaction.commitments[1] != ZERO || transaction.commitments.length != 1 || transaction.nullifiers.length != 0 || transaction.compressedSecrets.length != 0 || nZeroProof == 4 || // We assume that 3 out of the 4 proof elements can be a valid ZERO. Deals with exception cases transaction.historicRootBlockNumberL2[0] != 0 || transaction.historicRootBlockNumberL2[1] != 0, 'This deposit transaction type is valid' ); } // the transaction type single transfer is challenged to not be valid function libChallengeTransactionTypeSingleTransfer(Structures.Transaction memory transaction) public pure { uint256 nZeroCompressedSecrets; for (uint256 i = 0; i < transaction.compressedSecrets.length; i++) { if (transaction.compressedSecrets[i] == 0) nZeroCompressedSecrets++; } uint256 nZeroProof; for (uint256 i = 0; i < transaction.proof.length; i++) { if (transaction.proof[i] == 0) nZeroProof++; } require( transaction.tokenId != ZERO || transaction.value != 0 || transaction.ercAddress == ZERO || transaction.recipientAddress != ZERO || transaction.commitments[0] == ZERO || transaction.commitments[1] != ZERO || transaction.commitments.length != 1 || transaction.nullifiers[0] == ZERO || transaction.nullifiers[1] != ZERO || transaction.nullifiers.length != 1 || nZeroCompressedSecrets == 8 || // We assume that 7 out of the 8 compressed secrets elements can be a valid ZERO. Deals with exception cases nZeroProof == 4 || // We assume that 3 out of the 4 proof elements can be a valid ZERO. Deals with exception cases transaction.historicRootBlockNumberL2[1] != 0, // If this is a single, the second historicBlockNumber needs to be zero 'This single transfer transaction type is valid' ); } // the transaction type double transfer is challenged to not be valid function libChallengeTransactionTypeDoubleTransfer(Structures.Transaction memory transaction) public pure { uint256 nZeroCompressedSecrets; for (uint256 i = 0; i < transaction.compressedSecrets.length; i++) { if (transaction.compressedSecrets[i] == 0) nZeroCompressedSecrets++; } uint256 nZeroProof; for (uint256 i = 0; i < transaction.proof.length; i++) { if (transaction.proof[i] == 0) nZeroProof++; } require( transaction.tokenId != ZERO || transaction.value != 0 || transaction.ercAddress == ZERO || transaction.recipientAddress != ZERO || transaction.commitments[0] == ZERO || transaction.commitments[1] == ZERO || transaction.commitments.length != 2 || transaction.nullifiers[0] == ZERO || transaction.nullifiers[1] == ZERO || transaction.nullifiers.length != 2 || nZeroCompressedSecrets == 8 || // We assume that 7 out of the 8 compressed secrets elements can be a valid ZERO. Deals with exception cases nZeroProof == 4, // We assume that 3 out of the 4 proof elements can be a valid ZERO. Deals with exception cases 'This double transfer transaction type is valid' ); } // the transaction type withdraw is challenged to not be valid function libChallengeTransactionTypeWithdraw(Structures.Transaction memory transaction) public pure { uint256 nZeroProof; for (uint256 i = 0; i < transaction.proof.length; i++) { if (transaction.proof[i] == 0) nZeroProof++; } require( (transaction.tokenId == ZERO && transaction.value == 0) || transaction.ercAddress == ZERO || transaction.recipientAddress == ZERO || transaction.commitments.length != 0 || transaction.nullifiers[0] == ZERO || transaction.nullifiers[1] != ZERO || transaction.nullifiers.length != 1 || transaction.compressedSecrets.length != 0 || nZeroProof == 4 || // We assume that 3 out of the 4 proof elements can be a valid ZERO. Deals with exception cases transaction.historicRootBlockNumberL2[1] != 0, // A withdraw has a similar constraint as a single transfer 'This withdraw transaction type is valid' ); } function libChallengeProofVerification( Structures.Transaction calldata transaction, uint256[2] memory roots, uint256[8] memory proof, uint256[] memory vk ) internal { libCheckCompressedProof(transaction.proof, proof); // TODO convert from uint[8] to uint[] - make unnecessary. uint256[] memory proof1 = new uint256[](proof.length); for (uint256 i = 0; i < proof.length; i++) { proof1[i] = proof[i]; } uint256[] memory publicInputs = Utils.getPublicInputs(transaction, roots); require(!Verifier.verify(proof1, publicInputs, vk), 'This proof appears to be valid'); } function libCheckCompressedProof( uint256[4] memory compressedProof, uint256[8] memory uncompressedProof ) internal pure { // check equality by comparing hashes (cheaper than comparing elements) require( keccak256(abi.encodePacked(compressedProof)) == keccak256(abi.encodePacked(Utils.compressProof(uncompressedProof))), 'Cannot recreate compressed proof from uncompressed proof' ); } function libChallengeNullifier( Structures.Transaction memory tx1, uint256 nullifierIndex1, Structures.Transaction memory tx2, uint256 nullifierIndex2 ) public pure { require( tx1.nullifiers[nullifierIndex1] == tx2.nullifiers[nullifierIndex2], 'Not matching nullifiers' ); require( Utils.hashTransaction(tx1) != Utils.hashTransaction(tx2), 'Transactions need to be different' ); } }
next check the sibling path is valid and get the Frontier At last, we can check if the root itself is correct!
function libChallengeNewRootCorrect( Structures.Block memory blockL2, Structures.Transaction[] memory transactions ) public pure { bool valid; bytes32[33] memory _frontier; (valid, _frontier) = MerkleTree_Stateless.checkPath( Utils.filterCommitments(priorBlockTransactions), frontierPriorBlock, priorBlockL2.leafCount, priorBlockL2.root ); require(valid, 'The sibling path is invalid'); uint256 commitmentIndex = priorBlockL2.leafCount + Utils.filterCommitments(priorBlockTransactions).length; (bytes32 root, , ) = MerkleTree_Stateless.insertLeaves( Utils.filterCommitments(transactions), _frontier, commitmentIndex ); require(root != blockL2.root, 'The root is actually fine'); }
12,779,828
[ 1, 4285, 866, 326, 10841, 589, 353, 923, 471, 336, 326, 16465, 2453, 2380, 1142, 16, 732, 848, 866, 309, 326, 1365, 6174, 353, 3434, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2561, 18359, 1908, 2375, 16147, 12, 203, 3639, 7362, 1823, 18, 1768, 3778, 1203, 48, 22, 16, 203, 3639, 7362, 1823, 18, 3342, 8526, 3778, 8938, 203, 565, 262, 1071, 16618, 288, 203, 3639, 1426, 923, 31, 203, 3639, 1731, 1578, 63, 3707, 65, 3778, 389, 10211, 2453, 31, 203, 3639, 261, 877, 16, 389, 10211, 2453, 13, 273, 31827, 2471, 67, 5000, 12617, 18, 1893, 743, 12, 203, 5411, 6091, 18, 2188, 5580, 1346, 12, 17927, 1768, 14186, 3631, 203, 5411, 6641, 2453, 25355, 1768, 16, 203, 5411, 6432, 1768, 48, 22, 18, 12070, 1380, 16, 203, 5411, 6432, 1768, 48, 22, 18, 3085, 203, 3639, 11272, 203, 3639, 2583, 12, 877, 16, 296, 1986, 10841, 589, 353, 2057, 8284, 203, 3639, 2254, 5034, 23274, 1016, 273, 6432, 1768, 48, 22, 18, 12070, 1380, 397, 6091, 18, 2188, 5580, 1346, 12, 17927, 1768, 14186, 2934, 2469, 31, 203, 3639, 261, 3890, 1578, 1365, 16, 269, 262, 273, 203, 5411, 31827, 2471, 67, 5000, 12617, 18, 6387, 1682, 6606, 12, 203, 7734, 6091, 18, 2188, 5580, 1346, 12, 20376, 3631, 203, 7734, 389, 10211, 2453, 16, 203, 7734, 23274, 1016, 203, 5411, 11272, 203, 3639, 2583, 12, 3085, 480, 1203, 48, 22, 18, 3085, 16, 296, 1986, 1365, 353, 6013, 11079, 8284, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./interfaces/IVoucherKernel.sol"; import "./interfaces/IVoucherSets.sol"; import "./interfaces/ICashier.sol"; /** * @title Voucher sets implemented as ERC-1155 */ contract VoucherSets is IVoucherSets, ERC1155, Ownable, Pausable { address private voucherKernelAddress; //address of the VoucherKernel contract address private cashierAddress; //address of the Cashier contract string private contractUri; event LogVoucherKernelSet(address _newVoucherKernel, address _triggeredBy); event LogCashierSet(address _newCashier, address _triggeredBy); event LogContractUriSet(string _contractUri, address _triggeredBy); modifier onlyFromVoucherKernel() { require(msg.sender == voucherKernelAddress, "UNAUTHORIZED_VK"); _; } modifier notZeroAddress(address _address) { require(_address != address(0), "ZERO_ADDRESS"); _; } /** * @notice Construct and initialze the contract. * @param _uri metadata uri * @param _cashierAddress address of the associated Cashier contract * @param _voucherKernelAddress address of the associated Voucher Kernel contract */ constructor(string memory _uri, address _cashierAddress, address _voucherKernelAddress) ERC1155(_uri) notZeroAddress(_cashierAddress) notZeroAddress(_voucherKernelAddress) { cashierAddress = _cashierAddress; voucherKernelAddress = _voucherKernelAddress; emit LogCashierSet(_cashierAddress, msg.sender); emit LogVoucherKernelSet(_voucherKernelAddress, msg.sender); } /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only BR contract is in control of this function. */ function pause() external override onlyOwner { _pause(); } /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only BR contract is in control of this function. */ function unpause() external override onlyOwner { _unpause(); } /** * @notice Transfers amount of _tokenId from-to addresses with safety call. * If _to is a smart contract, will call onERC1155Received * @dev ERC-1155 * @param _from Source address * @param _to Destination address * @param _tokenId ID of the token * @param _value Transfer amount * @param _data Additional data forwarded to onERC1155Received if _to is a contract */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, uint256 _value, bytes calldata _data ) public override (ERC1155, IERC1155) { require(balanceOf(_from, _tokenId) == _value, "IQ"); //invalid qty super.safeTransferFrom(_from, _to, _tokenId, _value, _data); ICashier(cashierAddress).onVoucherSetTransfer( _from, _to, _tokenId, _value ); } /** @notice Transfers amount of _tokenId from-to addresses with safety call. If _to is a smart contract, will call onERC1155BatchReceived @dev ERC-1155 @param _from Source address @param _to Destination address @param _tokenIds array of token IDs @param _values array of transfer amounts @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _tokenIds, uint256[] calldata _values, bytes calldata _data ) public override (ERC1155, IERC1155) { //Thes checks need to be called first. Code is duplicated, but super.safeBatchTransferFrom //must be called at the end because otherwise the balance check in the loop will always fail require(_tokenIds.length == _values.length, "ERC1155: ids and amounts length mismatch"); require(_to != address(0), "ERC1155: transfer to the zero address"); require( _from == _msgSender() || isApprovedForAll(_from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); //This is inefficient because it repeats the loop in ERC1155.safeBatchTransferFrom. However, //there is no other good way to call the Boson Protocol cashier contract inside the loop. //Doing a full override by copying the ERC1155 code doesn't work because the _balances mapping //is private instead of internal and can't be accesssed from this child contract for (uint256 i = 0; i < _tokenIds.length; ++i) { uint256 tokenId = _tokenIds[i]; uint256 value = _values[i]; //A voucher set's quantity cannot be partionally transferred. It's all or nothing require(balanceOf(_from, tokenId) == value, "IQ"); //invalid qty ICashier(cashierAddress).onVoucherSetTransfer( _from, _to, tokenId, value ); } super.safeBatchTransferFrom(_from, _to, _tokenIds, _values, _data); } // // // // // // // // // STANDARD - UTILS // // // // // // // // /** * @notice Mint an amount of a desired token * Currently no restrictions as to who is allowed to mint - so, it is public. * @dev ERC-1155 * @param _to owner of the minted token * @param _tokenId ID of the token to be minted * @param _value Amount of the token to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mint( address _to, uint256 _tokenId, uint256 _value, bytes memory _data ) external override onlyFromVoucherKernel { _mint(_to, _tokenId, _value, _data); } /** * @notice Batch minting of tokens * Currently no restrictions as to who is allowed to mint - so, it is public. * @dev ERC-1155 * @param _to The address that will own the minted token * @param _tokenIds IDs of the tokens to be minted * @param _values Amounts of the tokens to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mintBatch( address _to, uint256[] calldata _tokenIds, uint256[] calldata _values, bytes calldata _data ) external onlyFromVoucherKernel { //require approved minter _mintBatch(_to, _tokenIds, _values, _data); } /** * @notice Burn an amount of tokens with the given ID * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenId ID of the token * @param _value Amount of the token */ function burn( address _account, uint256 _tokenId, uint256 _value ) external override onlyFromVoucherKernel { _burn(_account, _tokenId, _value); } /** * @notice Batch burn an amounts of tokens * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenIds IDs of the tokens * @param _values Amounts of the tokens */ function burnBatch( address _account, uint256[] calldata _tokenIds, uint256[] calldata _values ) external onlyFromVoucherKernel { _burnBatch(_account, _tokenIds, _values); } // // // // // // // // // METADATA EXTENSIONS // // // // // // // // /** * @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. * @param _newUri New uri to be used */ function setUri(string memory _newUri) external onlyOwner { _setURI(_newUri); } /** * @notice Setting a contractURI for OpenSea collections integration. * @param _contractUri The contract URI to be used */ function setContractUri(string memory _contractUri) external onlyOwner { require(bytes(_contractUri).length != 0, "INVALID_VALUE"); contractUri = _contractUri; emit LogContractUriSet(_contractUri, msg.sender); } // // // // // // // // // UTILS // // // // // // // // /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external override onlyOwner notZeroAddress(_voucherKernelAddress) whenPaused { voucherKernelAddress = _voucherKernelAddress; emit LogVoucherKernelSet(_voucherKernelAddress, msg.sender); } /** * @notice Set the address of the cashier contract * @param _cashierAddress The Cashier contract */ function setCashierAddress(address _cashierAddress) external override onlyOwner notZeroAddress(_cashierAddress) whenPaused { cashierAddress = _cashierAddress; emit LogCashierSet(_cashierAddress, msg.sender); } /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view override returns (address) { return voucherKernelAddress; } /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view override returns (address) { return cashierAddress; } /** * @notice Get the contractURI for Opensea collections integration * @return Contract URI */ function contractURI() public view returns (string memory) { return contractUri; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 () { 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.7.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 SafeMath for uint256; 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; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @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) external 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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(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 `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } 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 `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @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(to).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(to).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 pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * _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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./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: LGPL-3.0-or-later pragma solidity 0.7.6; import "./../UsingHelpers.sol"; interface IVoucherKernel { /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only Cashier contract is in control of this function. */ function pause() external; /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only Cashier contract is in control of this function. */ function unpause() external; /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (but not in prototype). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external returns (uint256); /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external; /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token * @param _to recipient, one of {ISSUER, HOLDER, POOL} * @param _amount amount that was released in the transaction */ function setDepositsReleased( uint256 _tokenIdVoucher, Entity _to, uint256 _amount ) external; /** * @notice Tells if part of the deposit, belonging to entity, was released already * @param _tokenIdVoucher ID of the voucher token * @param _to recipient, one of {ISSUER, HOLDER, POOL} */ function isDepositReleased(uint256 _tokenIdVoucher, Entity _to) external returns (bool); /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function refund(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Issue a complain for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function complain(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher set (seller) */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external returns (uint256); /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external; /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external; /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external; /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external; /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external; /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Voucher Sets token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external; /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external; /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view returns (bytes32); /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view returns (uint256, uint256); /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) external pure returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) external view returns (bytes32); /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view returns ( uint256, uint256, uint256 ); /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _owner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner) external view returns (uint256); /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) external view returns (PaymentMethod); /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view returns ( uint8, bool, bool, uint256, uint256 ); /** * @notice Get the holder of a supply * @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the issuer of a voucher * @param _voucherTokenId ID of the voucher token * @return Address of the seller, when voucher was created */ function getVoucherSeller(uint256 _voucherTokenId) external view returns (address); /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view returns (address); /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Get address of the Boson Router contract to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view returns (address); /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view returns (address); /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's */ function getTokenNonce(address _seller) external view returns (uint256); /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view returns (uint256); /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view returns (uint256); /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view returns (uint256); /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view returns ( bytes32, uint256, uint256, uint256, uint256 ); /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view returns (bytes32); /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view returns (address); /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; interface IVoucherSets is IERC1155, IERC1155MetadataURI { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Mint an amount of a desired token * Currently no restrictions as to who is allowed to mint - so, it is external. * @dev ERC-1155 * @param _to owner of the minted token * @param _tokenId ID of the token to be minted * @param _value Amount of the token to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mint( address _to, uint256 _tokenId, uint256 _value, bytes calldata _data ) external; /** * @notice Burn an amount of tokens with the given ID * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenId ID of the token * @param _value Amount of the token */ function burn( address _account, uint256 _tokenId, uint256 _value ) external; /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "./../UsingHelpers.sol"; interface ICashier { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; function canUnpause() external view returns (bool); /** * @notice Trigger withdrawals of what funds are releasable * The caller of this function triggers transfers to all involved entities (pool, issuer, token holder), also paying for gas. * @dev This function would be optimized a lot, here verbose for readability. * @param _tokenIdVoucher ID of a voucher token (ERC-721) to try withdraw funds from */ function withdraw(uint256 _tokenIdVoucher) external; function withdrawSingle(uint256 _tokenIdVoucher, Entity _to) external; /** * @notice External function for withdrawing deposits. Caller must be the seller of the goods, otherwise reverts. * @notice Seller triggers withdrawals of remaining deposits for a given supply, in case the voucher set is no longer in exchange. * @param _tokenIdSupply an ID of a supply token (ERC-1155) which will be burned and deposits will be returned for * @param _burnedQty burned quantity that the deposits should be withdrawn for * @param _messageSender owner of the voucher set */ function withdrawDepositsSe( uint256 _tokenIdSupply, uint256 _burnedQty, address payable _messageSender ) external; /** * @notice Get the amount in escrow of an address * @param _account The address of an account to query * @return The balance in escrow */ function getEscrowAmount(address _account) external view returns (uint256); /** * @notice Update the amount in escrow of an address with the new value, based on VoucherSet/Voucher interaction * @param _account The address of an account to query */ function addEscrowAmount(address _account) external payable; /** * @notice Update the amount in escrowTokens of an address with the new value, based on VoucherSet/Voucher interaction * @param _token The address of a token to query * @param _account The address of an account to query * @param _newAmount New amount to be set */ function addEscrowTokensAmount( address _token, address _account, uint256 _newAmount ) external; /** * @notice Hook which will be triggered when a _tokenIdVoucher will be transferred. Escrow funds should be allocated to the new owner. * @param _from prev owner of the _tokenIdVoucher * @param _to next owner of the _tokenIdVoucher * @param _tokenIdVoucher _tokenIdVoucher that has been transferred */ function onVoucherTransfer( address _from, address _to, uint256 _tokenIdVoucher ) external; /** * @notice After the transfer happens the _tokenSupplyId should be updated in the promise. Escrow funds for the deposits (If in ETH) should be allocated to the new owner as well. * @param _from prev owner of the _tokenSupplyId * @param _to next owner of the _tokenSupplyId * @param _tokenSupplyId _tokenSupplyId for transfer * @param _value qty which has been transferred */ function onVoucherSetTransfer( address _from, address _to, uint256 _tokenSupplyId, uint256 _value ) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Boson Router contract * @return Address of Boson Router contract */ function getBosonRouterAddress() external view returns (address); /** * @notice Get the address of the Vouchers contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view returns (address); /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view returns (address); /** * @notice Ensure whether or not contract has been set to disaster state * @return disasterState */ function isDisasterStateSet() external view returns (bool); /** * @notice Get the amount in escrow of an address * @param _token The address of a token to query * @param _account The address of an account to query * @return The balance in escrow */ function getEscrowTokensAmount(address _token, address _account) external view returns (uint256); /** * @notice Set the address of the BR contract * @param _bosonRouterAddress The address of the Cashier contract */ function setBosonRouterAddress(address _bosonRouterAddress) external; /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the VoucherKernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external; /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Voucher Sets token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external; } // 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.7.0; import "../../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 pragma solidity ^0.7.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 pragma solidity ^0.7.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 () { // 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.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, 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.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) { // 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.7.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: LGPL-3.0-or-later pragma solidity 0.7.6; // Those are the payment methods we are using throughout the system. // Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise enum PaymentMethod { ETHETH, ETHTKN, TKNETH, TKNTKN } enum Entity {ISSUER, HOLDER, POOL} enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT} /* Status of the voucher in 8 bits: [6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL] */ enum Condition {NOT_SET, BALANCE, OWNERSHIP} //Describes what kind of condition must be met for a conditional commit struct ConditionalCommitInfo { uint256 conditionalTokenId; uint256 threshold; Condition condition; address gateAddress; bool registerConditionalCommit; } uint8 constant ONE = 1; struct VoucherDetails { uint256 tokenIdSupply; uint256 tokenIdVoucher; address issuer; address holder; uint256 price; uint256 depositSe; uint256 depositBu; PaymentMethod paymentMethod; VoucherStatus currStatus; } struct VoucherStatus { address seller; uint8 status; bool isPaymentReleased; bool isDepositsReleased; DepositsReleased depositReleased; uint256 complainPeriodStart; uint256 cancelFaultPeriodStart; } struct DepositsReleased { uint8 status; uint248 releasedAmount; } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state. * @param _status current status of a voucher. */ function isStateCommitted(uint8 _status) pure returns (bool) { return _status == determineStatus(0, VoucherState.COMMIT); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state. * @param _status current status of a voucher. */ function isStateRedemptionSigned(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state. * @param _status current status of a voucher. */ function isStateRefunded(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state. * @param _status current status of a voucher. */ function isStateExpired(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at. * @param _status current status of a voucher. * @param _idx status to compare. */ function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) { return (_status >> uint8(_idx)) & ONE == 1; } /** * @notice Set voucher status. * @param _status previous status. * @param _changeIdx next status. */ function determineStatus(uint8 _status, VoucherState _changeIdx) pure returns (uint8) { return _status | (ONE << uint8(_changeIdx)); }
* @notice Batch minting of tokens Currently no restrictions as to who is allowed to mint - so, it is public. @dev ERC-1155 @param _to The address that will own the minted token @param _tokenIds IDs of the tokens to be minted @param _values Amounts of the tokens to be minted @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract/require approved minter
function mintBatch( address _to, uint256[] calldata _tokenIds, uint256[] calldata _values, bytes calldata _data ) external onlyFromVoucherKernel { _mintBatch(_to, _tokenIds, _values, _data); }
14,468,874
[ 1, 4497, 312, 474, 310, 434, 2430, 15212, 1158, 17499, 487, 358, 10354, 353, 2935, 358, 312, 474, 300, 1427, 16, 518, 353, 1071, 18, 225, 4232, 39, 17, 2499, 2539, 225, 389, 869, 1021, 1758, 716, 903, 4953, 326, 312, 474, 329, 1147, 225, 389, 2316, 2673, 7115, 434, 326, 2430, 358, 506, 312, 474, 329, 225, 389, 2372, 16811, 87, 434, 326, 2430, 358, 506, 312, 474, 329, 225, 389, 892, 15119, 501, 19683, 358, 603, 654, 39, 2499, 2539, 4497, 8872, 309, 389, 869, 353, 279, 6835, 19, 6528, 20412, 1131, 387, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 4497, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 2316, 2673, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 2372, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 3903, 1338, 1265, 19585, 11286, 288, 203, 203, 3639, 389, 81, 474, 4497, 24899, 869, 16, 389, 2316, 2673, 16, 389, 2372, 16, 389, 892, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x35c556d2700CE48fC3D3C1736B28bd15dC5cFC59/sources/TrueRatingAgency.sol
* @dev Only loans in Running state/
modifier onlyNotRunningLoans(address id) { require(status(id) != LoanStatus.Running, "TrueRatingAgency: Loan is currently running"); _; }
3,990,262
[ 1, 3386, 437, 634, 316, 20480, 919, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1248, 7051, 1504, 634, 12, 2867, 612, 13, 288, 203, 3639, 2583, 12, 2327, 12, 350, 13, 480, 3176, 304, 1482, 18, 7051, 16, 315, 5510, 20388, 2577, 2075, 30, 3176, 304, 353, 4551, 3549, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x09bf15edb5F6EED7081c96ed79246Ff723B86b00/sources/contracts/erc1155_test.sol
_artists[_tokenIdCounter.current()] = artists;
_mint(account, _tokenIdCounter.current(), amount, data);
649,346
[ 1, 67, 485, 1486, 63, 67, 2316, 548, 4789, 18, 2972, 1435, 65, 273, 3688, 1486, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 81, 474, 12, 4631, 16, 389, 2316, 548, 4789, 18, 2972, 9334, 3844, 16, 501, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } 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); } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /* Provides support and utilities for contract management Note that a managed contract must also have an owner */ contract Managed is Owned { address public manager; address public newManager; event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** @dev constructor */ function Managed() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // allows execution by either the owner or the manager only modifier ownerOrManagerOnly { require(msg.sender == owner || msg.sender == manager); _; } /** @dev allows transferring the contract management the new manager still needs to accept the transfer can only be called by the contract manager @param _newManager new contract manager */ function transferManagement(address _newManager) public ownerOrManagerOnly { require(_newManager != manager); newManager = _newManager; } /** @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); emit ManagerUpdate(manager, newManager); manager = newManager; newManager = address(0); } } /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; } /** Id definitions for bancor contract features Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The smart token controller is an upgradable part of the smart token that allows more functionality as well as fixes for bugs/exploits. Once it accepts ownership of the token, it becomes the token's sole controller that can execute any of its functions. To upgrade the controller, ownership must be transferred to a new controller, along with any relevant data. The smart token must be set on construction and cannot be changed afterwards. Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access. Note that the controller can transfer token ownership to a new controller that doesn't allow executing any function on the token, for a trustless solution. Doing that will also remove the owner's ability to upgrade the controller. */ contract SmartTokenController is TokenHolder { ISmartToken public token; // smart token /** @dev constructor */ function SmartTokenController(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { assert(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { assert(token.owner() != address(this)); _; } /** @dev allows transferring the token ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } /** @dev used by a new owner to accept a token ownership transfer can only be called by the contract owner */ function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } /** @dev disables/enables token transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } /** @dev withdraws tokens held by the controller and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawFromToken( IERC20Token _token, address _to, uint256 _amount ) public ownerOnly { ITokenHolder(token).withdrawTokens(_token, _to, _amount); } } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Converter v0.9 The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves. ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. The converter is upgradable (just like any SmartTokenController). WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits or with very small numbers because of precision loss Open issues: - Front-running attacks are currently mitigated by the following mechanisms: - minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction - gas price limit prevents users from having control over the order of execution - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer Other potential solutions might include a commit/reveal based schemes - Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds { uint32 private constant MAX_WEIGHT = 1000000; uint64 private constant MAX_CONVERSION_FEE = 1000000; struct Connector { uint256 virtualBalance; // connector virtual balance uint32 weight; // connector weight, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner bool isSet; // used to tell if the mapping element is defined } string public version = '0.9'; string public converterType = 'bancor'; IContractRegistry public registry; // contract registry contract IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public connectorTokens; // ERC20 standard token addresses IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH mapping (address => Connector) public connectors; // connector token addresses -> connector data uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100% uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public conversionsEnabled = true; // true if token conversions is enabled, false if not IERC20Token[] private convertPath; // triggered when a conversion between two tokens occurs event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); // triggered after a conversion with new price data event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); // triggered when the conversion fee is updated event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** @dev constructor @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector */ function BancorConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public SmartTokenController(_token) validAddress(_registry) validMaxConversionFee(_maxConversionFee) { registry = _registry; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_connectorToken != address(0)) addConnector(_connectorToken, _connectorWeight, false); } // validates a connector token address - verifies that the address belongs to one of the connector tokens modifier validConnector(IERC20Token _address) { require(connectors[_address].isSet); _; } // validates a token address - verifies that the address belongs to one of the convertible tokens modifier validToken(IERC20Token _address) { require(_address == token || connectors[_address].isSet); _; } // validates maximum conversion fee modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; } // validates connector weight range modifier validConnectorWeight(uint32 _weight) { require(_weight > 0 && _weight <= MAX_WEIGHT); _; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { assert(conversionsEnabled); _; } // allows execution by the BancorNetwork contract only modifier bancorNetworkOnly { IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); require(msg.sender == address(bancorNetwork)); _; } /** @dev returns the number of connector tokens defined @return number of connector tokens */ function connectorTokenCount() public view returns (uint16) { return uint16(connectorTokens.length); } /* @dev allows the owner to update the registry contract address @param _registry address of a bancor converter registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update & enable the conversion whitelist contract address when set, only addresses that are whitelisted are actually allowed to use the converter note that the whitelist check is actually done by the BancorNetwork contract @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) { conversionWhitelist = _whitelist; } /* @dev allows the manager to update the quick buy path @param _path new quick buy path, see conversion path format in the bancorNetwork contract */ function setQuickBuyPath(IERC20Token[] _path) public ownerOnly validConversionPath(_path) { quickBuyPath = _path; } /* @dev allows the manager to clear the quick buy path */ function clearQuickBuyPath() public ownerOnly { quickBuyPath.length = 0; } /** @dev returns the length of the quick buy path array @return quick buy path length */ function getQuickBuyPathLength() public view returns (uint256) { return quickBuyPath.length; } /** @dev disables the entire conversion functionality this is a safety mechanism in case of a emergency can only be called by the manager @param _disable true to disable conversions, false to re-enable them */ function disableConversions(bool _disable) public ownerOrManagerOnly { conversionsEnabled = !_disable; } /** @dev updates the current conversion fee can only be called by the manager @param _conversionFee new conversion fee, represented in ppm */ function setConversionFee(uint32 _conversionFee) public ownerOrManagerOnly validConversionFee(_conversionFee) { emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /* @dev given a return amount, returns the amount minus the conversion fee @param _amount return amount @param _magnitude 1 for standard conversion, 2 for cross connector conversion @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude; } /** @dev defines a new connector for the token can only be called by the owner while the converter is inactive @param _token address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it */ function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validConnectorWeight(_weight) { require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input connectors[_token].virtualBalance = 0; connectors[_token].weight = _weight; connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance; connectors[_token].isPurchaseEnabled = true; connectors[_token].isSet = true; connectorTokens.push(_token); totalConnectorWeight += _weight; } /** @dev updates one of the token connectors can only be called by the owner @param _connectorToken address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it @param _virtualBalance new connector's virtual balance */ function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validConnector(_connectorToken) validConnectorWeight(_weight) { Connector storage connector = connectors[_connectorToken]; require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input totalConnectorWeight = totalConnectorWeight - connector.weight + _weight; connector.weight = _weight; connector.isVirtualBalanceEnabled = _enableVirtualBalance; connector.virtualBalance = _virtualBalance; } /** @dev disables purchasing with the given connector token in case the connector token got compromised can only be called by the owner note that selling is still enabled regardless of this flag and it cannot be disabled by the owner @param _connectorToken connector token contract address @param _disable true to disable the token, false to re-enable it */ function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable) public ownerOnly validConnector(_connectorToken) { connectors[_connectorToken].isPurchaseEnabled = !_disable; } /** @dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance @param _connectorToken connector token contract address @return connector balance */ function getConnectorBalance(IERC20Token _connectorToken) public view validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this); } /** @dev returns the expected return for converting a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @return expected conversion return amount */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 connectors return getCrossConnectorReturn(_fromToken, _toToken, _amount); } /** @dev returns the expected return for buying the token for a connector token @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @return expected purchase return amount */ function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; require(connector.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling the token for one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @return expected sale return amount */ function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling one of the connector tokens for another connector token @param _fromConnectorToken contract address of the connector token to convert from @param _toConnectorToken contract address of the connector token to convert to @param _sellAmount amount to sell (in the from connector token) @return expected sale return amount (in the to connector token) */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount) public view active validConnector(_fromConnectorToken) validConnector(_toConnectorToken) returns (uint256) { Connector storage fromConnector = connectors[_fromConnectorToken]; Connector storage toConnector = connectors[_toConnectorToken]; require(toConnector.isPurchaseEnabled); // validate input uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken); uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount); // return the amount minus the conversion fee // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) return getFinalAmount(amount, 2); } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public bancorNetworkOnly conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // conversion between 2 connectors uint256 amount = getCrossConnectorReturn(_fromToken, _toToken, _amount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update the source token virtual balance if relevant Connector storage fromConnector = connectors[_fromToken]; if (fromConnector.isVirtualBalanceEnabled) fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount); // update the target token virtual balance if relevant Connector storage toConnector = connectors[_toToken]; if (toConnector.isVirtualBalanceEnabled) toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount); // ensure that the trade won't deplete the connector balance uint256 toConnectorBalance = getConnectorBalance(_toToken); assert(amount < toConnectorBalance); // transfer funds from the caller in the from connector token assert(_fromToken.transferFrom(msg.sender, this, _amount)); // transfer funds to the caller in the to connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_toToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 2)); dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both connectors emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight); emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight); return amount; } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { convertPath = [_fromToken, token, _toToken]; return quickConvert(convertPath, _amount, _minReturn); } /** @dev buys the token by depositing one of its connector tokens @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return buy return amount */ function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount); // transfer funds from the caller in the connector token assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount)); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev sells the token by withdrawing from one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero @return sell return amount */ function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount = getSaleReturn(_connectorToken, _sellAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // ensure that the trade will only deplete the connector balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeSub(connector.virtualBalance, amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_connectorToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable validConversionPath(_path) returns (uint256) { return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps validating if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps validating if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps validating if the signature is legit @return tokens issued in return */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { IERC20Token fromToken = _path[0]; IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); // we need to transfer the source tokens from the caller to the BancorNetwork contract, // so it can execute the conversion on behalf of the caller if (msg.value == 0) { // not ETH, send the source tokens to the BancorNetwork contract // if the token is the smart token, no allowance is required - destroy the tokens // from the caller and issue them to the BancorNetwork contract if (fromToken == token) { token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract } else { // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount)); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s); } // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** @dev helper, dispatches the Conversion event @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount purchased/sold (in the source token) @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount <= 2 ** 255); emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount)); } /** @dev fallback, buys the smart token with ETH note that the purchase will use the price at the time of the purchase */ function() payable public { quickConvert(quickBuyPath, msg.value, 1); } } /* Bancor Converter Factory interface */ contract IBancorConverterFactory { function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns (address); } /* Bancor Converter Factory */ contract BancorConverterFactory is IBancorConverterFactory { // triggered when a new converter is created event NewConverter(address indexed _converter, address indexed _owner); /** @dev constructor */ function BancorConverterFactory() public { } /** @dev creates a new converter with the given arguments and transfers the ownership and management to the sender. @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector @return a new converter */ function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns(address converterAddress) { BancorConverter converter = new BancorConverter( _token, _registry, _maxConversionFee, _connectorToken, _connectorWeight ); converter.transferOwnership(msg.sender); converter.transferManagement(msg.sender); address _converterAddress = address(converter); emit NewConverter(_converterAddress, msg.sender); return _converterAddress; } }
/ initialize supported features
function BancorConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public SmartTokenController(_token) validAddress(_registry) validMaxConversionFee(_maxConversionFee) { registry = _registry; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_connectorToken != address(0)) addConnector(_connectorToken, _connectorWeight, false); }
14,568
[ 1, 19, 4046, 3260, 4467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 304, 3850, 5072, 12, 203, 3639, 4437, 81, 485, 1345, 389, 2316, 16, 203, 3639, 467, 8924, 4243, 389, 9893, 16, 203, 3639, 2254, 1578, 389, 1896, 6814, 14667, 16, 203, 3639, 467, 654, 39, 3462, 1345, 389, 23159, 1345, 16, 203, 3639, 2254, 1578, 389, 23159, 6544, 203, 565, 262, 203, 3639, 1071, 203, 3639, 19656, 1345, 2933, 24899, 2316, 13, 203, 3639, 923, 1887, 24899, 9893, 13, 203, 3639, 923, 2747, 6814, 14667, 24899, 1896, 6814, 14667, 13, 203, 565, 288, 203, 3639, 4023, 273, 389, 9893, 31, 203, 3639, 467, 8924, 8696, 4467, 273, 467, 8924, 8696, 12, 9893, 18, 588, 1887, 12, 8924, 2673, 18, 6067, 2849, 1268, 67, 18257, 55, 10019, 203, 203, 3639, 309, 261, 7139, 480, 1758, 12, 20, 3719, 203, 5411, 4467, 18, 7589, 8696, 12, 4595, 2673, 18, 2248, 2204, 2560, 67, 2248, 5757, 67, 16861, 7085, 16, 638, 1769, 203, 203, 3639, 943, 6814, 14667, 273, 389, 1896, 6814, 14667, 31, 203, 203, 3639, 309, 261, 67, 23159, 1345, 480, 1758, 12, 20, 3719, 203, 5411, 527, 7487, 24899, 23159, 1345, 16, 389, 23159, 6544, 16, 629, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc9E77ef4a304B39bEa702b882E701b757dCd3730/sources/home/paras/roaring-leaders/contracts/RoaringRoccstars.sol
Mint Roaring Roccstar NFTs during pre-sale/
function presaleMint(uint256 numberOfTokens) public payable { require(preSaleIsActive, "Presale not live"); require(_presaleMints[msg.sender] + numberOfTokens <= maxPresaleMintsPerWallet, "Presale limit"); require(_mintCounter.current() + numberOfTokens <= maxMintSupply, "Max supply"); require(mintPrice * numberOfTokens <= msg.value, "Incorrect ether"); _presaleMints[msg.sender] += numberOfTokens; for(uint256 i = 0; i < numberOfTokens; i++) { _mintCounter.increment(); _tokenIdCounter.increment(); _safeMint(msg.sender, _tokenIdCounter.current()); emit CubMinted(_tokenIdCounter.current()); } }
4,982,853
[ 1, 49, 474, 534, 83, 5968, 534, 25049, 10983, 423, 4464, 87, 4982, 675, 17, 87, 5349, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4075, 5349, 49, 474, 12, 11890, 5034, 7922, 5157, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 1484, 30746, 2520, 3896, 16, 315, 12236, 5349, 486, 8429, 8863, 203, 3639, 2583, 24899, 12202, 5349, 49, 28142, 63, 3576, 18, 15330, 65, 397, 7922, 5157, 1648, 943, 12236, 5349, 49, 28142, 2173, 16936, 16, 315, 12236, 5349, 1800, 8863, 203, 3639, 2583, 24899, 81, 474, 4789, 18, 2972, 1435, 397, 7922, 5157, 1648, 943, 49, 474, 3088, 1283, 16, 315, 2747, 14467, 8863, 203, 3639, 2583, 12, 81, 474, 5147, 380, 7922, 5157, 1648, 1234, 18, 1132, 16, 315, 16268, 225, 2437, 8863, 203, 203, 3639, 389, 12202, 5349, 49, 28142, 63, 3576, 18, 15330, 65, 1011, 7922, 5157, 31, 203, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 7922, 5157, 31, 277, 27245, 288, 203, 5411, 389, 81, 474, 4789, 18, 15016, 5621, 203, 5411, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 389, 2316, 548, 4789, 18, 2972, 10663, 203, 5411, 3626, 385, 373, 49, 474, 329, 24899, 2316, 548, 4789, 18, 2972, 10663, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /* Interface for ERC20 Tokens */ contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } /* Interface for the DMEX base contract */ contract EtherMium { function getReserve(address token, address user) returns (uint256); function setReserve(address token, address user, uint256 amount) returns (bool); function availableBalanceOf(address token, address user) returns (uint256); function balanceOf(address token, address user) returns (uint256); function setBalance(address token, address user, uint256 amount) returns (bool); function getAffiliate(address user) returns (address); function getInactivityReleasePeriod() returns (uint256); function getMakerTakerBalances(address token, address maker, address taker) returns (uint256[4]); function getEtmTokenAddress() returns (address); function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) returns (bool); function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) returns (bool); function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) returns (bool); } // The DMEX Futures Contract contract Exchange { function assert(bool assertion) pure { if (!assertion) { throw; } } // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) pure returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } address public owner; // holds the address of the contract owner // Event fired when the owner of the contract is changed event SetOwner(address indexed previousOwner, address indexed newOwner); // Allows only the owner of the contract to execute the function modifier onlyOwner { assert(msg.sender == owner); _; } // Changes the owner of the contract function setOwner(address newOwner) onlyOwner { emit SetOwner(owner, newOwner); owner = newOwner; } // Owner getter function function getOwner() view returns (address out) { return owner; } mapping (address => bool) public admins; // mapping of admin addresses mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity address public feeAccount; // the account that receives the trading fees address public exchangeContract; // the address of the main EtherMium contract uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) struct FuturesAsset { string name; // the name of the traded asset (ex. ETHUSD) address baseToken; // the token for collateral string priceUrl; // the url where the price of the asset will be taken for settlement string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"}) bool inversed; // if true, the price from the priceUrl will be inversed (i.e price = 1/priceUrl) bool disabled; // if true, the asset cannot be used in contract creation (when price url no longer valid) } function createFuturesAsset(string name, address baseToken, string priceUrl, string pricePath, bool inversed) onlyAdmin returns (bytes32) { bytes32 futuresAsset = keccak256(this, name, baseToken, priceUrl, pricePath, inversed); if (futuresAssets[futuresAsset].disabled) throw; // asset already exists and is disabled futuresAssets[futuresAsset] = FuturesAsset({ name : name, baseToken : baseToken, priceUrl : priceUrl, pricePath : pricePath, inversed : inversed, disabled : false }); emit FuturesAssetCreated(futuresAsset, name, baseToken, priceUrl, pricePath, inversed); return futuresAsset; } struct FuturesContract { bytes32 asset; // the hash of the underlying asset object uint256 expirationBlock; // futures contract expiration block uint256 closingPrice; // the closing price for the futures contract bool closed; // is the futures contract closed (0 - false, 1 - true) bool broken; // if someone has forced release of funds the contract is marked as broken and can no longer close positions (0-false, 1-true) uint256 floorPrice; // the minimum price that can be traded on the contract, once price is reached the contract expires and enters settlement state uint256 capPrice; // the maximum price that can be traded on the contract, once price is reached the contract expires and enters settlement state uint256 multiplier; // the multiplier price, used when teh trading pair doesn't have the base token in it (eg. BTCUSD with ETH as base token, multiplier will be the ETHBTC price) } function createFuturesContract(bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier) onlyAdmin returns (bytes32) { bytes32 futuresContract = keccak256(this, asset, expirationBlock, floorPrice, capPrice, multiplier); if (futuresContracts[futuresContract].expirationBlock > 0) throw; // contract already exists futuresContracts[futuresContract] = FuturesContract({ asset : asset, expirationBlock : expirationBlock, closingPrice : 0, closed : false, broken : false, floorPrice : floorPrice, capPrice : capPrice, multiplier : multiplier }); emit FuturesContractCreated(futuresContract, asset, expirationBlock, floorPrice, capPrice, multiplier); return futuresContract; } mapping (bytes32 => FuturesAsset) public futuresAssets; // mapping of futuresAsset hash to FuturesAsset structs mapping (bytes32 => FuturesContract) public futuresContracts; // mapping of futuresContract hash to FuturesContract structs mapping (bytes32 => uint256) public positions; // mapping of user addresses to position hashes to position enum Errors { INVALID_PRICE, // Order prices don't match INVALID_SIGNATURE, // Signature is invalid ORDER_ALREADY_FILLED, // Order was already filled GAS_TOO_HIGH, // Too high gas fee OUT_OF_BALANCE, // User doesn't have enough balance for the operation FUTURES_CONTRACT_EXPIRED, // Futures contract already expired FLOOR_OR_CAP_PRICE_REACHED, // The floor price or the cap price for the futures contract was reached POSITION_ALREADY_EXISTS, // User has an open position already UINT48_VALIDATION, // Size or price bigger than an Uint48 FAILED_ASSERTION // Assertion failed } event FuturesTrade(bool side, uint256 size, uint256 price, bytes32 indexed futuresContract, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event FuturesContractClosed(bytes32 indexed futuresContract, uint256 closingPrice); event FuturesForcedRelease(bytes32 indexed futuresContract, bool side, address user); event FuturesAssetCreated(bytes32 indexed futuresAsset, string name, address baseToken, string priceUrl, string pricePath, bool inversed); event FuturesContractCreated(bytes32 indexed futuresContract, bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier); // Fee change event event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee); // Log event, logs errors in contract execution (for internal use) event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event LogErrorLight(uint8 indexed errorId); event LogUint(uint8 id, uint256 value); event LogBool(uint8 id, bool value); event LogAddress(uint8 id, address value); // Constructor function, initializes the contract and sets the core variables function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_) { owner = msg.sender; feeAccount = feeAccount_; makerFee = makerFee_; takerFee = takerFee_; exchangeContract = exchangeContract_; } // Changes the fees function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner { require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1% makerFee = makerFee_; takerFee = takerFee_; emit FeeChange(makerFee, takerFee); } // Adds or disables an admin account function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } // Allows for admins only to call the function modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function() external { throw; } function validateUint48(uint256 val) returns (bool) { if (val != uint48(val)) return false; return true; } function validateUint64(uint256 val) returns (bool) { if (val != uint64(val)) return false; return true; } function validateUint128(uint256 val) returns (bool) { if (val != uint128(val)) return false; return true; } // Structure that holds order values, used inside the trade() function struct FuturesOrderPair { uint256 makerNonce; // maker order nonce, makes the order unique uint256 takerNonce; // taker order nonce uint256 takerGasFee; // taker gas fee, taker pays the gas uint256 takerIsBuying; // true/false taker is the buyer address maker; // address of the maker address taker; // address of the taker bytes32 makerOrderHash; // hash of the maker order bytes32 takerOrderHash; // has of the taker order uint256 makerAmount; // trade amount for maker uint256 takerAmount; // trade amount for taker uint256 makerPrice; // maker order price in wei (18 decimal precision) uint256 takerPrice; // taker order price in wei (18 decimal precision) bytes32 futuresContract; // the futures contract being traded address baseToken; // the address of the base token for futures contract uint256 floorPrice; // floor price of futures contract uint256 capPrice; // cap price of futures contract bytes32 makerPositionHash; // hash for maker position bytes32 makerInversePositionHash; // hash for inverse maker position bytes32 takerPositionHash; // hash for taker position bytes32 takerInversePositionHash; // hash for inverse taker position } // Structure that holds trade values, used inside the trade() function struct FuturesTradeValues { uint256 qty; // amount to be trade uint256 makerProfit; // holds maker profit value uint256 makerLoss; // holds maker loss value uint256 takerProfit; // holds taker profit value uint256 takerLoss; // holds taker loss value uint256 makerBalance; // holds maker balance value uint256 takerBalance; // holds taker balance value uint256 makerReserve; // holds taker reserved value uint256 takerReserve; // holds taker reserved value } // Opens/closes futures positions function futuresTrade( uint8[2] v, bytes32[4] rs, uint256[8] tradeValues, address[2] tradeAddresses, bool takerIsBuying, bytes32 futuresContractHash ) onlyAdmin returns (uint filledTakerTokenAmount) { /* tradeValues [0] makerNonce [1] takerNonce [2] takerGasFee [3] takerIsBuying [4] makerAmount [5] takerAmount [6] makerPrice [7] takerPrice tradeAddresses [0] maker [1] taker */ FuturesOrderPair memory t = FuturesOrderPair({ makerNonce : tradeValues[0], takerNonce : tradeValues[1], takerGasFee : tradeValues[2], takerIsBuying : tradeValues[3], makerAmount : tradeValues[4], takerAmount : tradeValues[5], makerPrice : tradeValues[6], takerPrice : tradeValues[7], maker : tradeAddresses[0], taker : tradeAddresses[1], // futuresContract user amount price side nonce makerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[0], tradeValues[4], tradeValues[6], !takerIsBuying, tradeValues[0]), takerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[1], tradeValues[5], tradeValues[7], takerIsBuying, tradeValues[1]), futuresContract : futuresContractHash, baseToken : futuresAssets[futuresContracts[futuresContractHash].asset].baseToken, floorPrice : futuresContracts[futuresContractHash].floorPrice, capPrice : futuresContracts[futuresContractHash].capPrice, // user futuresContractHash side makerPositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, !takerIsBuying), makerInversePositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, takerIsBuying), takerPositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, takerIsBuying), takerInversePositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, !takerIsBuying) }); //--> 44 000 // Valifate size and price values if (!validateUint128(t.makerAmount) || !validateUint128(t.takerAmount) || !validateUint64(t.makerPrice) || !validateUint64(t.takerPrice)) { emit LogError(uint8(Errors.UINT48_VALIDATION), t.makerOrderHash, t.takerOrderHash); return 0; } // Check if futures contract has expired already if (block.number > futuresContracts[t.futuresContract].expirationBlock || futuresContracts[t.futuresContract].closed == true || futuresContracts[t.futuresContract].broken == true) { emit LogError(uint8(Errors.FUTURES_CONTRACT_EXPIRED), t.makerOrderHash, t.takerOrderHash); return 0; // futures contract is expired } // Checks the signature for the maker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker) { emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks the signature for the taker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker) { emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // check prices if ((!takerIsBuying && t.makerPrice < t.takerPrice) || (takerIsBuying && t.takerPrice < t.makerPrice)) { emit LogError(uint8(Errors.INVALID_PRICE), t.makerOrderHash, t.takerOrderHash); return 0; // prices don't match } //--> 54 000 uint256[4] memory balances = EtherMium(exchangeContract).getMakerTakerBalances(t.baseToken, t.maker, t.taker); // Initializing trade values structure FuturesTradeValues memory tv = FuturesTradeValues({ qty : 0, makerProfit : 0, makerLoss : 0, takerProfit : 0, takerLoss : 0, makerBalance : balances[0], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker), takerBalance : balances[1], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker), makerReserve : balances[2], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker), takerReserve : balances[3] //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker), }); //--> 60 000 // check if floor price or cap price was reached if (futuresContracts[t.futuresContract].floorPrice >= t.makerPrice || futuresContracts[t.futuresContract].capPrice <= t.makerPrice) { // attepting price outside range emit LogError(uint8(Errors.FLOOR_OR_CAP_PRICE_REACHED), t.makerOrderHash, t.takerOrderHash); return 0; } // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders // and open inverse positions tv.qty = min(safeSub(t.makerAmount, orderFills[t.makerOrderHash]), safeSub(t.takerAmount, orderFills[t.takerOrderHash])); if (positionExists(t.makerInversePositionHash) && positionExists(t.takerInversePositionHash)) { tv.qty = min(tv.qty, min(retrievePosition(t.makerInversePositionHash)[0], retrievePosition(t.takerInversePositionHash)[0])); } else if (positionExists(t.makerInversePositionHash)) { tv.qty = min(tv.qty, retrievePosition(t.makerInversePositionHash)[0]); } else if (positionExists(t.takerInversePositionHash)) { tv.qty = min(tv.qty, retrievePosition(t.takerInversePositionHash)[0]); } //--> 64 000 if (tv.qty == 0) { // no qty left on orders emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // Cheks that gas fee is not higher than 10% if (safeMul(t.takerGasFee, 20) > calculateTradeValue(tv.qty, t.makerPrice, t.futuresContract)) { emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash); return 0; } // takerGasFee too high // check if users have open positions already // if (positionExists(t.makerPositionHash) || positionExists(t.takerPositionHash)) // { // // maker already has the position open, first must close existing position before opening a new one // emit LogError(uint8(Errors.POSITION_ALREADY_EXISTS), t.makerOrderHash, t.takerOrderHash); // return 0; // } //--> 66 000 /*------------- Maker long, Taker short -------------*/ if (!takerIsBuying) { // position actions for maker if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash)) { // check if maker has enough balance if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // create new position recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 1, block.number); updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // make address ], t.makerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee 0, // profit 0, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ true, // newPostion (if true position is new) true, // side (if true - long) false // increase position (if true) ] ); } else { if (positionExists(t.makerPositionHash)) { // check if maker has enough balance // if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, // safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve)) if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // increase position size updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice); updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // make address ], t.makerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee 0, // profit 0, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ false, // newPostion (if true position is new) true, // side (if true - long) true // increase position (if true) ] ); } else { // close/partially close existing position updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0); if (t.makerPrice < retrievePosition(t.makerInversePositionHash)[1]) { // user has made a profit //tv.makerProfit = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice; tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true); } else { // user has made a loss //tv.makerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice; tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true); } updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // make address ], t.makerInversePositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee tv.makerProfit, // profit tv.makerLoss, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ false, // newPostion (if true position is new) true, // side (if true - long) false // increase position (if true) ] ); } } // position actions for taker if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash)) { // check if taker has enough balance // if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve)) if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // create new position recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 0, block.number); updateBalances( t.futuresContract, [ t.baseToken, // base token t.taker // make address ], t.takerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee 0, // profit 0, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ true, // newPostion (if true position is new) false, // side (if true - long) false // increase position (if true) ] ); } else { if (positionExists(t.takerPositionHash)) { // check if taker has enough balance //if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve)) if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // increase position size updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice); updateBalances( t.futuresContract, [ t.baseToken, // base token t.taker // make address ], t.takerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee 0, // profit 0, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ false, // newPostion (if true position is new) false, // side (if true - long) true // increase position (if true) ] ); } else { // close/partially close existing position updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0); if (t.makerPrice > retrievePosition(t.takerInversePositionHash)[1]) { // user has made a profit //tv.takerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice; tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false); } else { // user has made a loss //tv.takerLoss = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice; tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false); } updateBalances( t.futuresContract, [ t.baseToken, // base token t.taker // make address ], t.takerInversePositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee tv.takerProfit, // profit tv.takerLoss, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ false, // newPostion (if true position is new) false, // side (if true - long) false // increase position (if true) ] ); } } } /*------------- Maker short, Taker long -------------*/ else { //LogUint(1, safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty)); return; // position actions for maker if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash)) { // check if maker has enough balance //if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve)) if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // create new position recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 0, block.number); updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // make address ], t.makerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee 0, // profit 0, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ true, // newPostion (if true position is new) false, // side (if true - long) false // increase position (if true) ] ); } else { if (positionExists(t.makerPositionHash)) { // check if maker has enough balance //if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve)) if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // increase position size updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice); updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // make address ], t.makerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee 0, // profit 0, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ false, // newPostion (if true position is new) false, // side (if true - long) true // increase position (if true) ] ); } else { // close/partially close existing position updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0); if (t.makerPrice > retrievePosition(t.makerInversePositionHash)[1]) { // user has made a profit //tv.makerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice; tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false); } else { // user has made a loss //tv.makerLoss = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice; tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false); } updateBalances( t.futuresContract, [ t.baseToken, // base token t.maker // user address ], t.makerInversePositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price makerFee, // fee tv.makerProfit, // profit tv.makerLoss, // loss tv.makerBalance, // balance 0, // gasFee tv.makerReserve // reserve ], [ false, // newPostion (if true position is new) false, // side (if true - long) false // increase position (if true) ] ); } } // position actions for taker if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash)) { // check if taker has enough balance // if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve)) if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // create new position recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 1, block.number); updateBalances( t.futuresContract, [ t.baseToken, // base token t.taker // user address ], t.takerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee 0, // profit 0, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ true, // newPostion (if true position is new) true, // side (if true - long) false // increase position (if true) ] ); } else { if (positionExists(t.takerPositionHash)) { // check if taker has enough balance //if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve)) if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) { // maker out of balance emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash); return 0; } // increase position size updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice); updateBalances( t.futuresContract, [ t.baseToken, // base token t.taker // user address ], t.takerPositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee 0, // profit 0, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ false, // newPostion (if true position is new) true, // side (if true - long) true // increase position (if true) ] ); } else { // close/partially close existing position updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0); if (t.makerPrice < retrievePosition(t.takerInversePositionHash)[1]) { // user has made a profit //tv.takerProfit = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice; tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true); } else { // user has made a loss //tv.takerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice; tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true); } updateBalances( t.futuresContract, [ t.baseToken, // base toke t.taker // user address ], t.takerInversePositionHash, // position hash [ tv.qty, // qty t.makerPrice, // price takerFee, // fee tv.takerProfit, // profit tv.takerLoss, // loss tv.takerBalance, // balance t.takerGasFee, // gasFee tv.takerReserve // reserve ], [ false, // newPostion (if true position is new) true, // side (if true - long) false // increase position (if true) ] ); } } } //--> 220 000 orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount //--> 264 000 emit FuturesTrade(takerIsBuying, tv.qty, t.makerPrice, t.futuresContract, t.makerOrderHash, t.takerOrderHash); return tv.qty; } function calculateProfit(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256) { bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed; uint256 multiplier = futuresContracts[futuresContractHash].multiplier; if (side) { if (inversed) { return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice; } else { return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18; } } else { if (inversed) { return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice; } else { return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18; } } } function calculateTradeValue(uint256 qty, uint256 price, bytes32 futuresContractHash) returns (uint256) { bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed; uint256 multiplier = futuresContracts[futuresContractHash].multiplier; if (inversed) { return qty * 1e10; } else { return safeMul(safeMul(safeMul(qty, price), 1e2), multiplier) / 1e18 ; } } function calculateLoss(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256) { bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed; uint256 multiplier = futuresContracts[futuresContractHash].multiplier; if (side) { if (inversed) { return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice; } else { return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18; } } else { if (inversed) { return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice; } else { return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18; } } } function calculateCollateral (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, bytes32 futuresContractHash) view returns (uint256) { bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed; uint256 multiplier = futuresContracts[futuresContractHash].multiplier; if (side) { // long if (inversed) { return safeMul(safeSub(tradePrice, limitPrice), qty) / limitPrice; } else { return safeMul(safeMul(safeSub(tradePrice, limitPrice), qty), multiplier) / 1e8 / 1e18; } } else { // short if (inversed) { return safeMul(safeSub(limitPrice, tradePrice), qty) / limitPrice; } else { return safeMul(safeMul(safeSub(limitPrice, tradePrice), qty), multiplier) / 1e8 / 1e18; } } } function calculateFee (uint256 qty, uint256 tradePrice, uint256 fee, bytes32 futuresContractHash) returns (uint256) { return safeMul(calculateTradeValue(qty, tradePrice, futuresContractHash), fee) / 1e18 / 1e10; } function checkEnoughBalance (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, uint256 fee, uint256 gasFee, bytes32 futuresContractHash, uint256 availableBalance) view returns (bool) { if (side) { // long if (safeAdd( safeAdd( calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash), //safeMul(qty, fee) / (1 ether) calculateFee(qty, tradePrice, fee, futuresContractHash) ) * 1e10, gasFee ) > availableBalance) { return false; } } else { // short if (safeAdd( safeAdd( calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash), //safeMul(qty, fee) / (1 ether) calculateFee(qty, tradePrice, fee, futuresContractHash) ) * 1e10, gasFee ) > availableBalance) { return false; } } return true; } // Executes multiple trades in one transaction, saves gas fees function batchFuturesTrade( uint8[2][] v, bytes32[4][] rs, uint256[8][] tradeValues, address[2][] tradeAddresses, bool[] takerIsBuying, bytes32[] futuresContractHash ) onlyAdmin { for (uint i = 0; i < tradeAddresses.length; i++) { futuresTrade( v[i], rs[i], tradeValues[i], tradeAddresses[i], takerIsBuying[i], futuresContractHash[i] ); } } // Update user balance function updateBalances (bytes32 futuresContract, address[2] addressValues, bytes32 positionHash, uint256[8] uintValues, bool[3] boolValues) private { /* addressValues [0] baseToken [1] user uintValues [0] qty [1] price [2] fee [3] profit [4] loss [5] balance [6] gasFee [7] reserve boolValues [0] newPostion [1] side [2] increase position */ // qty * price * fee // uint256 pam[0] = safeMul(safeMul(uintValues[0], uintValues[1]), uintValues[2]) / (1 ether); // uint256 collateral; // pam = [fee value, collateral] uint256[2] memory pam = [safeAdd(calculateFee(uintValues[0], uintValues[1], uintValues[2], futuresContract) * 1e10, uintValues[6]), 0]; // LogUint(100, uintValues[3]); // LogUint(9, uintValues[2]); // LogUint(7, safeMul(uintValues[0], uintValues[2]) / (1 ether)); // return; // Position is new or position is increased if (boolValues[0] || boolValues[2]) { if (boolValues[1]) { //addReserve(addressValues[0], addressValues[1], uintValues[ 7], safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0])); // reserve collateral on user //pam[1] = safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0]) / futuresContracts[futuresContract].floorPrice; pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, uintValues[1], uintValues[0], true, futuresContract); } else { //addReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0])); // reserve collateral on user //pam[1] = safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0]) / futuresContracts[futuresContract].capPrice; pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, uintValues[1], uintValues[0], false, futuresContract); } subBalanceAddReserve(addressValues[0], addressValues[1], pam[0], safeAdd(pam[1],1)); // if (uintValues[6] > 0) // { // subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]); // } // else // { // subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]); // } //subBalance(addressValues[0], addressValues[1], uintValues[5], feeVal); // deduct user maker/taker fee // Position exists } else { if (retrievePosition(positionHash)[2] == 0) { // original position was short //subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]))); // remove freed collateral from reserver //pam[1] = safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1])) / futuresContracts[futuresContract].capPrice; pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], uintValues[0], false, futuresContract); // LogUint(120, uintValues[0]); // LogUint(121, futuresContracts[futuresContract].capPrice); // LogUint(122, retrievePosition(positionHash)[1]); // LogUint(123, uintValues[3]); // profit // LogUint(124, uintValues[4]); // loss // LogUint(125, safeAdd(uintValues[4], pam[0])); // LogUint(12, pam[1] ); //return; } else { // original position was long //subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice))); //pam[1] = safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice)) / futuresContracts[futuresContract].floorPrice; pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], uintValues[0], true, futuresContract); } // LogUint(41, uintValues[3]); // LogUint(42, uintValues[4]); // LogUint(43, pam[0]); // return; if (uintValues[3] > 0) { // profi > 0 if (pam[0] <= uintValues[3]*1e10) { //addBalance(addressValues[0], addressValues[1], uintValues[5], safeSub(uintValues[3], pam[0])); // add profit to user balance addBalanceSubReserve(addressValues[0], addressValues[1], safeSub(uintValues[3]*1e10, pam[0]), pam[1]); } else { subBalanceSubReserve(addressValues[0], addressValues[1], safeSub(pam[0], uintValues[3]*1e10), pam[1]); } } else { // loss >= 0 //subBalance(addressValues[0], addressValues[1], uintValues[5], safeAdd(uintValues[4], pam[0])); // deduct loss from user balance subBalanceSubReserve(addressValues[0], addressValues[1], safeAdd(uintValues[4]*1e10, pam[0]), pam[1]); // deduct loss from user balance } //} } addBalance(addressValues[0], feeAccount, EtherMium(exchangeContract).balanceOf(addressValues[0], feeAccount), pam[0]); // send fee to feeAccount } function recordNewPosition (bytes32 positionHash, uint256 size, uint256 price, uint256 side, uint256 block) private { if (!validateUint128(size) || !validateUint64(price)) { throw; } uint256 character = uint128(size); character |= price<<128; character |= side<<192; character |= block<<208; positions[positionHash] = character; } function retrievePosition (bytes32 positionHash) public view returns (uint256[4]) { uint256 character = positions[positionHash]; uint256 size = uint256(uint128(character)); uint256 price = uint256(uint64(character>>128)); uint256 side = uint256(uint16(character>>192)); uint256 entryBlock = uint256(uint48(character>>208)); return [size, price, side, entryBlock]; } function updatePositionSize(bytes32 positionHash, uint256 size, uint256 price) private { uint256[4] memory pos = retrievePosition(positionHash); if (size > pos[0]) { // position is increasing in size recordNewPosition(positionHash, size, safeAdd(safeMul(pos[0], pos[1]), safeMul(price, safeSub(size, pos[0]))) / size, pos[2], pos[3]); } else { // position is decreasing in size recordNewPosition(positionHash, size, pos[1], pos[2], pos[3]); } } function positionExists (bytes32 positionHash) internal view returns (bool) { //LogUint(3,retrievePosition(positionHash)[0]); if (retrievePosition(positionHash)[0] == 0) { return false; } else { return true; } } // This function allows the user to manually release collateral in case the oracle service does not provide the price during the inactivityReleasePeriod function forceReleaseReserve (bytes32 futuresContract, bool side) public { if (futuresContracts[futuresContract].expirationBlock == 0) throw; if (futuresContracts[futuresContract].expirationBlock > block.number) throw; if (safeAdd(futuresContracts[futuresContract].expirationBlock, EtherMium(exchangeContract).getInactivityReleasePeriod()) > block.number) throw; bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side); if (retrievePosition(positionHash)[1] == 0) throw; futuresContracts[futuresContract].broken = true; address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken; if (side) { subReserve( baseToken, msg.sender, EtherMium(exchangeContract).getReserve(baseToken, msg.sender), //safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, futuresContract) ); } else { subReserve( baseToken, msg.sender, EtherMium(exchangeContract).getReserve(baseToken, msg.sender), //safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, futuresContract) ); } updatePositionSize(positionHash, 0, 0); //EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), ); //reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], positions[msg.sender][positionHash].collateral); emit FuturesForcedRelease(futuresContract, side, msg.sender); } function addBalance(address token, address user, uint256 balance, uint256 amount) private { EtherMium(exchangeContract).setBalance(token, user, safeAdd(balance, amount)); } function subBalance(address token, address user, uint256 balance, uint256 amount) private { EtherMium(exchangeContract).setBalance(token, user, safeSub(balance, amount)); } function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) private { EtherMium(exchangeContract).subBalanceAddReserve(token, user, subBalance, addReserve * 1e10); } function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) private { EtherMium(exchangeContract).addBalanceSubReserve(token, user, addBalance, subReserve * 1e10); } function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) private { // LogUint(31, subBalance); // LogUint(32, subReserve); // return; EtherMium(exchangeContract).subBalanceSubReserve(token, user, subBalance, subReserve * 1e10); } function addReserve(address token, address user, uint256 reserve, uint256 amount) private { //reserve[token][user] = safeAdd(reserve[token][user], amount); EtherMium(exchangeContract).setReserve(token, user, safeAdd(reserve, amount * 1e10)); } function subReserve(address token, address user, uint256 reserve, uint256 amount) private { //reserve[token][user] = safeSub(reserve[token][user], amount); EtherMium(exchangeContract).setReserve(token, user, safeSub(reserve, amount * 1e10)); } function getMakerTakerBalances(address maker, address taker, address token) public view returns (uint256[4]) { return [ EtherMium(exchangeContract).balanceOf(token, maker), EtherMium(exchangeContract).getReserve(token, maker), EtherMium(exchangeContract).balanceOf(token, taker), EtherMium(exchangeContract).getReserve(token, taker) ]; } function getMakerTakerPositions(bytes32 makerPositionHash, bytes32 makerInversePositionHash, bytes32 takerPosition, bytes32 takerInversePosition) public view returns (uint256[4][4]) { return [ retrievePosition(makerPositionHash), retrievePosition(makerInversePositionHash), retrievePosition(takerPosition), retrievePosition(takerInversePosition) ]; } struct FuturesClosePositionValues { uint256 reserve; // amount to be trade uint256 balance; // holds maker profit value uint256 floorPrice; // holds maker loss value uint256 capPrice; // holds taker profit value uint256 closingPrice; // holds taker loss value bytes32 futuresContract; // the futures contract hash } function closeFuturesPosition (bytes32 futuresContract, bool side) { bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side); if (futuresContracts[futuresContract].closed == false && futuresContracts[futuresContract].expirationBlock != 0) throw; // contract not yet settled if (retrievePosition(positionHash)[1] == 0) throw; // position not found if (retrievePosition(positionHash)[0] == 0) throw; // position already closed uint256 profit; uint256 loss; address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken; FuturesClosePositionValues memory v = FuturesClosePositionValues({ reserve : EtherMium(exchangeContract).getReserve(baseToken, msg.sender), balance : EtherMium(exchangeContract).balanceOf(baseToken, msg.sender), floorPrice : futuresContracts[futuresContract].floorPrice, capPrice : futuresContracts[futuresContract].capPrice, closingPrice : futuresContracts[futuresContract].closingPrice, futuresContract : futuresContract }); // uint256 reserve = EtherMium(exchangeContract).getReserve(baseToken, msg.sender); // uint256 balance = EtherMium(exchangeContract).balanceOf(baseToken, msg.sender); // uint256 floorPrice = futuresContracts[futuresContract].floorPrice; // uint256 capPrice = futuresContracts[futuresContract].capPrice; // uint256 closingPrice = futuresContracts[futuresContract].closingPrice; //uint256 fee = safeMul(safeMul(retrievePosition(positionHash)[0], v.closingPrice), takerFee) / (1 ether); uint256 fee = calculateFee(retrievePosition(positionHash)[0], v.closingPrice, takerFee, futuresContract); // close long position if (side == true) { // LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender)); // LogUint(12, safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice); // return; // reserve = reserve - (entryPrice - floorPrice) * size; //subReserve(baseToken, msg.sender, EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[positionHash].size)); subReserve( baseToken, msg.sender, v.reserve, //safeMul(safeSub(retrievePosition(positionHash)[1], v.floorPrice), retrievePosition(positionHash)[0]) / v.floorPrice calculateCollateral(v.floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, v.futuresContract) ); //EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size)); //reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size)); if (v.closingPrice > retrievePosition(positionHash)[1]) { // user made a profit //profit = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice; profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false); // LogUint(15, profit); // LogUint(16, fee); // LogUint(17, safeSub(profit * 1e10, fee)); // return; addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10)); //EtherMium(exchangeContract).updateBalance(baseToken, msg.sender, safeAdd(EtherMium(exchangeContract).balanceOf(baseToken, msg.sender), profit); //tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit); } else { // user made a loss //loss = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice; loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false); subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10)); //tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss); } } // close short position else { // LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender)); // LogUint(12, safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice); // return; // reserve = reserve - (capPrice - entryPrice) * size; subReserve( baseToken, msg.sender, v.reserve, //safeMul(safeSub(v.capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.capPrice calculateCollateral(v.capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, v.futuresContract) ); //EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size)); //reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size)); if (v.closingPrice < retrievePosition(positionHash)[1]) { // user made a profit // profit = (entryPrice - closingPrice) * size // profit = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice; profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true); addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10)); //tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit); } else { // user made a loss // profit = (closingPrice - entryPrice) * size //loss = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice; loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true); subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10)); //tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss); } } addBalance(baseToken, feeAccount, EtherMium(exchangeContract).balanceOf(baseToken, feeAccount), fee * 1e10); // send fee to feeAccount updatePositionSize(positionHash, 0, 0); } /* string priceUrl; // the url where the price of the asset will be taken for settlement string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"}) bool multiplied; // if true, the price from the priceUrl will be multiplied by the multiplierPriceUrl string multiplierPriceUrl; // needed only if multiplied=true string multiplierPricePath; // same as pricePath bool inverseMultiplier; */ function closeFuturesContract (bytes32 futuresContract, uint256 price, uint256 multipliterPrice) onlyAdmin { uint256 closingPrice = price; if (futuresContracts[futuresContract].expirationBlock == 0) throw; // contract not found if (futuresContracts[futuresContract].closed == true) throw; // contract already closed if (futuresContracts[futuresContract].expirationBlock > block.number && closingPrice > futuresContracts[futuresContract].floorPrice && closingPrice < futuresContracts[futuresContract].capPrice) throw; // contract not yet expired futuresContracts[futuresContract].closingPrice = closingPrice; futuresContracts[futuresContract].closed = true; emit FuturesContractClosed(futuresContract, closingPrice); } // Returns the smaller of two values function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
mapping of user addresses to last transaction block
mapping (address => uint256) public lastActiveTransaction;
2,472,877
[ 1, 6770, 434, 729, 6138, 358, 1142, 2492, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 1142, 3896, 3342, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2019 ZeroEx Intl. 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.5.9; import "../src/LibBytes.sol"; contract TestLibBytes { using LibBytes for bytes; /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function publicPopLastByte(bytes memory b) public pure returns (bytes memory, bytes1 result) { result = b.popLastByte(); return (b, result); } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function publicEquals(bytes memory lhs, bytes memory rhs) public pure returns (bool equal) { equal = lhs.equals(rhs); return equal; } function publicEqualsPop1(bytes memory lhs, bytes memory rhs) public pure returns (bool equal) { lhs.popLastByte(); rhs.popLastByte(); equal = lhs.equals(rhs); return equal; } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function publicReadAddress( bytes memory b, uint256 index ) public pure returns (address result) { result = b.readAddress(index); return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function publicWriteAddress( bytes memory b, uint256 index, address input ) public pure returns (bytes memory) { b.writeAddress(index, input); return b; } /// @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 bytes32 value from byte array. function publicReadBytes32( bytes memory b, uint256 index ) public pure returns (bytes32 result) { result = b.readBytes32(index); return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function publicWriteBytes32( bytes memory b, uint256 index, bytes32 input ) public pure returns (bytes memory) { b.writeBytes32(index, input); return b; } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function publicReadUint256( bytes memory b, uint256 index ) public pure returns (uint256 result) { result = b.readUint256(index); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function publicWriteUint256( bytes memory b, uint256 index, uint256 input ) public pure returns (bytes memory) { b.writeUint256(index, input); return b; } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function publicReadBytes4( bytes memory b, uint256 index ) public pure returns (bytes4 result) { result = b.readBytes4(index); return result; } /// @dev Copies a block of memory from one location to another. /// @param mem Memory contents we want to apply memCopy to /// @param dest Destination offset into <mem>. /// @param source Source offset into <mem>. /// @param length Length of bytes to copy from <source> to <dest> /// @return mem Memory contents after calling memCopy. function testMemcpy( bytes memory mem, uint256 dest, uint256 source, uint256 length ) public // not external, we need input in memory pure returns (bytes memory) { // Sanity check. Overflows are not checked. require(source + length <= mem.length); require(dest + length <= mem.length); // Get pointer to memory contents uint256 offset = mem.contentAddress(); // Execute memCopy adjusted for memory array location LibBytes.memCopy(offset + dest, offset + source, length); // Return modified memory contents return mem; } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function publicSlice( bytes memory b, uint256 from, uint256 to ) public pure returns (bytes memory result, bytes memory original) { result = LibBytes.slice(b, from, to); return (result, b); } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function publicSliceDestructive( bytes memory b, uint256 from, uint256 to ) public pure returns (bytes memory result, bytes memory original) { result = LibBytes.sliceDestructive(b, from, to); return (result, b); } /// @dev Returns a byte array with an updated length. /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. /// @param extraBytes Bytes that are appended to end of b in memory. function publicWriteLength( bytes memory b, uint256 length, bytes memory extraBytes ) public pure returns (bytes memory) { uint256 bEnd = b.contentAddress() + b.length; LibBytes.memCopy(bEnd, extraBytes.contentAddress(), extraBytes.length); b.writeLength(length); return b; } function assertBytesUnchangedAfterLengthReset( bytes memory b, uint256 tempLength ) public pure { uint256 length = b.length; bytes memory bCopy = b.slice(0, length); b.writeLength(tempLength); b.writeLength(length); assert(b.equals(bCopy)); } }
@dev Returns a slices from a byte array. @param b The byte array to take a slice from. @param from The starting index for the slice (inclusive). @param to The final index for the slice (exclusive). @return result The slice containing bytes at indices [from, to)
function publicSlice( bytes memory b, uint256 from, uint256 to ) public pure returns (bytes memory result, bytes memory original) { result = LibBytes.slice(b, from, to); return (result, b); }
12,595,673
[ 1, 1356, 279, 12390, 628, 279, 1160, 526, 18, 225, 324, 1021, 1160, 526, 358, 4862, 279, 2788, 628, 18, 225, 628, 1021, 5023, 770, 364, 326, 2788, 261, 267, 9173, 2934, 225, 358, 1021, 727, 770, 364, 326, 2788, 261, 23792, 2934, 327, 563, 1021, 2788, 4191, 1731, 622, 4295, 306, 2080, 16, 358, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1071, 5959, 12, 203, 3639, 1731, 3778, 324, 16, 203, 3639, 2254, 5034, 628, 16, 203, 3639, 2254, 5034, 358, 203, 565, 262, 203, 3639, 1071, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 3778, 563, 16, 1731, 3778, 2282, 13, 203, 565, 288, 203, 3639, 563, 273, 10560, 2160, 18, 6665, 12, 70, 16, 628, 16, 358, 1769, 203, 3639, 327, 261, 2088, 16, 324, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/83/0x70d77fB99b9C7b3E41B2424e9Dcc898d49edbb4c/sources/contracts/CErc20.sol
* @notice Sender borrows assets from the protocol to their own address @param borrowAmount The amount of the underlying asset to borrow @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function borrow(uint256 borrowAmount) external returns (uint256) { return borrowInternal(borrowAmount); }
9,557,445
[ 1, 12021, 324, 280, 3870, 7176, 628, 326, 1771, 358, 3675, 4953, 1758, 225, 29759, 6275, 1021, 3844, 434, 326, 6808, 3310, 358, 29759, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 29759, 12, 11890, 5034, 29759, 6275, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 29759, 3061, 12, 70, 15318, 6275, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/250/0x1CD4f1E9336555af8398A2619E7ff2712E8F4046/sources/contracts/QissaFactory.sol
* Returns the list of projects, where project owner is involved in @param _projectOwner - parcId of a projectOwner to get the list from @return ProjectOwnerProjects - ProjectOwnerProjects, which contain a list of projects where they are involved in/
function getProjectsOfProjectOwner(address _projectOwner) external view returns (Project[] memory) { return ownerProjects[_projectOwner]; }
13,223,180
[ 1, 1356, 326, 666, 434, 10137, 16, 1625, 1984, 3410, 353, 24589, 316, 225, 389, 4406, 5541, 300, 779, 71, 548, 434, 279, 1984, 5541, 358, 336, 326, 666, 628, 327, 5420, 5541, 15298, 300, 5420, 5541, 15298, 16, 1492, 912, 279, 666, 434, 10137, 1625, 2898, 854, 24589, 316, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11080, 87, 951, 4109, 5541, 12, 2867, 389, 4406, 5541, 13, 3903, 1476, 1135, 261, 4109, 8526, 3778, 13, 288, 203, 3639, 327, 3410, 15298, 63, 67, 4406, 5541, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3F0303514da0C760CaBf836cAf4d7aaAfE0c587E/sources/NFT.sol
Do not remove this otherwise you will not be able to withdraw the funds. =============================================================================(bool hs, ) = payable(0x0d821eeb06847Eb83B8E63D9414eEF2dd3dDD300).call{value: address(this).balance * 1 /2}(""); =============================================================================
function withdraw() public onlyOwner { require(send()); require(os,"withdraw failed"); }
3,076,979
[ 1, 3244, 486, 1206, 333, 3541, 1846, 903, 486, 506, 7752, 358, 598, 9446, 326, 284, 19156, 18, 422, 22121, 12275, 12, 6430, 12670, 16, 262, 273, 8843, 429, 12, 20, 92, 20, 72, 28, 5340, 1340, 70, 7677, 5193, 27, 41, 70, 10261, 38, 28, 41, 4449, 40, 11290, 3461, 73, 26897, 22, 449, 23, 72, 5698, 19249, 2934, 1991, 95, 1132, 30, 1758, 12, 2211, 2934, 12296, 225, 404, 342, 22, 97, 2932, 8863, 422, 22121, 12275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 1435, 1071, 225, 1338, 5541, 288, 203, 377, 203, 565, 2583, 12, 4661, 10663, 203, 565, 2583, 12, 538, 10837, 1918, 9446, 2535, 8863, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x417cAeabf656a388EC60A7d3C61fF864179B5698/sources/project_/contracts/MoMABurn.sol
@notice burnAndMint use for burn old editions and mint new edition @param _burnedEditions - array of edition IDs to burn Check duplicate with others
function burnAndMint(uint256[] memory _burnedEditions) external { require(isBurnEnabled, "Burn and mint status is not enabled"); require( _burnedEditions.length == 3 || _burnedEditions.length == 6 || _burnedEditions.length == 9, "Invalid number of burning editions" ); FFArtworkInfo memory burnArtwork = getV2ContractArtwork( burnContractAddress, burnArtworkID ); for (uint256 i = 0; i < _burnedEditions.length; i++) { for (uint256 j = i + 1; j < _burnedEditions.length; j++) { if (_burnedEditions[i] == _burnedEditions[j]) { revert("Invalid burning editions"); } } require( bytes(burnArtwork.fingerprint).length != 0 && burnArtwork.editionSize > 0 && _burnedEditions[i] >= burnArtworkID && _burnedEditions[i] <= burnArtworkID + burnArtwork.editionSize, "Edition ID is not support for burning" ); FFV2(burnContractAddress).safeTransferFrom( _msgSender(), DEAD_ADDRESS, _burnedEditions[i] ); } address mintContractAddr = tier1ContractAddress; uint256 artworkID = tier1ArtworkID; if (_burnedEditions.length == 6) { mintContractAddr = tier2ContractAddress; artworkID = tier2ArtworkID; } if (_burnedEditions.length == 9) { mintContractAddr = tier3ContractAddress; artworkID = tier3ArtworkID; } FFV33(mintContractAddr).mintArtworkEdition(artworkID, _msgSender()); }
1,873,615
[ 1, 70, 321, 1876, 49, 474, 999, 364, 18305, 1592, 1675, 5029, 471, 312, 474, 394, 28432, 225, 389, 70, 321, 329, 41, 1460, 87, 300, 526, 434, 28432, 7115, 358, 18305, 2073, 6751, 598, 10654, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 1876, 49, 474, 12, 11890, 5034, 8526, 3778, 389, 70, 321, 329, 41, 1460, 87, 13, 3903, 288, 203, 3639, 2583, 12, 291, 38, 321, 1526, 16, 315, 38, 321, 471, 312, 474, 1267, 353, 486, 3696, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 389, 70, 321, 329, 41, 1460, 87, 18, 2469, 422, 890, 747, 203, 7734, 389, 70, 321, 329, 41, 1460, 87, 18, 2469, 422, 1666, 747, 203, 7734, 389, 70, 321, 329, 41, 1460, 87, 18, 2469, 422, 2468, 16, 203, 5411, 315, 1941, 1300, 434, 18305, 310, 1675, 5029, 6, 203, 3639, 11272, 203, 203, 3639, 6512, 4411, 1252, 966, 3778, 18305, 4411, 1252, 273, 11031, 22, 8924, 4411, 1252, 12, 203, 5411, 18305, 8924, 1887, 16, 203, 5411, 18305, 4411, 1252, 734, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 70, 321, 329, 41, 1460, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 5034, 525, 273, 277, 397, 404, 31, 525, 411, 389, 70, 321, 329, 41, 1460, 87, 18, 2469, 31, 525, 27245, 288, 203, 7734, 309, 261, 67, 70, 321, 329, 41, 1460, 87, 63, 77, 65, 422, 389, 70, 321, 329, 41, 1460, 87, 63, 78, 5717, 288, 203, 10792, 15226, 2932, 1941, 18305, 310, 1675, 5029, 8863, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 2583, 12, 203, 7734, 1731, 12, 70, 321, 4411, 1252, 18, 24716, 2934, 2469, 480, 374, 597, 203, 10792, 18305, 4411, 2 ]
./full_match/137/0xABBB4d0074C0361fBf7e07FD3d4d4e9cCCB9128f/sources/contracts/libraries/LimitOrderLibrary.sol
* @dev Structure for the updateOrder with parameters necessary to update limit order @param orderId order id to update @param depositAsset The address of the deposit token (collateral for margin trade or locked funds for spot) @param depositAmount The amount of deposit funds for deal @param makeDeposit Bool, add a collateral deposit within the current transaction @param leverage leverage for trading @param takeDepositFromWallet Bool, add a collateral deposit within the current transaction @param payFeeFromWallet A flag indicating whether the Limit Order fee is perfomed from a wallet or a protocol balance./
struct UpdateLimitOrderParams { uint256 orderId; address depositAsset; uint256 depositAmount; uint256 leverage; bool isProtocolFeeInPmx; bool takeDepositFromWallet; bool payFeeFromWallet; }
4,668,632
[ 1, 6999, 364, 326, 1089, 2448, 598, 1472, 4573, 358, 1089, 1800, 1353, 225, 20944, 1353, 612, 358, 1089, 225, 443, 1724, 6672, 1021, 1758, 434, 326, 443, 1724, 1147, 261, 12910, 2045, 287, 364, 7333, 18542, 578, 8586, 284, 19156, 364, 16463, 13, 225, 443, 1724, 6275, 1021, 3844, 434, 443, 1724, 284, 19156, 364, 10490, 225, 1221, 758, 1724, 9166, 16, 527, 279, 4508, 2045, 287, 443, 1724, 3470, 326, 783, 2492, 225, 884, 5682, 884, 5682, 364, 1284, 7459, 225, 4862, 758, 1724, 1265, 16936, 9166, 16, 527, 279, 4508, 2045, 287, 443, 1724, 3470, 326, 783, 2492, 225, 8843, 14667, 1265, 16936, 432, 2982, 11193, 2856, 326, 7214, 4347, 14036, 353, 14184, 362, 329, 628, 279, 9230, 578, 279, 1771, 11013, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 2315, 3039, 2448, 1370, 288, 203, 3639, 2254, 5034, 20944, 31, 203, 3639, 1758, 443, 1724, 6672, 31, 203, 3639, 2254, 5034, 443, 1724, 6275, 31, 203, 3639, 2254, 5034, 884, 5682, 31, 203, 3639, 1426, 353, 5752, 14667, 382, 52, 11023, 31, 203, 3639, 1426, 4862, 758, 1724, 1265, 16936, 31, 203, 3639, 1426, 8843, 14667, 1265, 16936, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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 {_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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { 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 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 granted `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}. * ==== */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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 pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { LS1Types } from '../lib/LS1Types.sol'; /** * @title LS1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract LS1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. LS1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. /// We also restrict other changes which could affect borrowers' repayment plans, such as /// modifications to the epoch schedule, or to borrower allocations. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => LS1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. LS1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => LS1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. Note: The shortfallCounter field is unused. LS1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; /// @dev Information about shortfalls that have occurred. LS1Types.Shortfall[] internal _SHORTFALLS_; // ============ Borrower Accounting ============ /// @dev The units allocated to each borrower. /// @dev Values are represented relative to total allocation, i.e. as hundredeths of a percent. /// Also, the total of the values contained in the mapping must always equal the total /// allocation (i.e. must sum to 10,000). mapping(address => LS1Types.StoredAllocation) internal _BORROWER_ALLOCATIONS_; /// @dev The token balance currently borrowed by the borrower. mapping(address => uint256) internal _BORROWED_BALANCES_; /// @dev The total token balance currently borrowed by borrowers. uint256 internal _TOTAL_BORROWED_BALANCE_; /// @dev Indicates whether a borrower is restricted from new borrowing. mapping(address => bool) internal _BORROWER_RESTRICTIONS_; // ============ Debt Accounting ============ /// @dev The debt balance owed to each staker. mapping(address => uint256) internal _STAKER_DEBT_BALANCES_; /// @dev The debt balance by borrower. mapping(address => uint256) internal _BORROWER_DEBT_BALANCES_; /// @dev The total debt balance of borrowers. uint256 internal _TOTAL_BORROWER_DEBT_BALANCE_; /// @dev The total debt amount repaid and not yet withdrawn. uint256 internal _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title LS1Types * @author dYdX * * @dev Structs used by the LiquidityStaking contract. */ library LS1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters representing a shortfall event. * * @param index Fraction of inactive funds converted into debt, scaled by SHORTFALL_INDEX_BASE. * @param epoch The epoch in which the shortfall occurred. */ struct Shortfall { uint16 epoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint224 index; // Note: Save on contract bytecode size by reusing uint224 instead of uint240. } /** * @dev A balance, possibly with a change scheduled for the next epoch. * Also includes cached index information for inactive balances. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. * @param shortfallCounter Incrementing counter of the next shortfall index to be applied. */ struct StoredBalance { uint16 currentEpoch; // Supports at least 1000 years given min epoch length of 6 days. uint112 currentEpochBalance; uint112 nextEpochBalance; uint16 shortfallCounter; // Only for staker inactive balances. At most one shortfall per epoch. } /** * @dev A borrower allocation, possibly with a change scheduled for the next epoch. */ struct StoredAllocation { uint16 currentEpoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint120 currentEpochAllocation; uint120 nextEpochAllocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract LS1Getters is LS1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The token balance currently borrowed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens borrowed. */ function getBorrowedBalance( address borrower ) external view returns (uint256) { return _BORROWED_BALANCES_[borrower]; } /** * @notice The total token balance borrowed by borrowers. * * @return The number of tokens borrowed. */ function getTotalBorrowedBalance() external view returns (uint256) { return _TOTAL_BORROWED_BALANCE_; } /** * @notice The debt balance owed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens owed. */ function getBorrowerDebtBalance( address borrower ) external view returns (uint256) { return _BORROWER_DEBT_BALANCES_[borrower]; } /** * @notice The total debt balance owed by borrowers. * * @return The number of tokens owed. */ function getTotalBorrowerDebtBalance() external view returns (uint256) { return _TOTAL_BORROWER_DEBT_BALANCE_; } /** * @notice The total debt repaid by borrowers and available for stakers to withdraw. * * @return The number of tokens available. */ function getTotalDebtAvailableToWithdraw() external view returns (uint256) { return _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } /** * @notice Check whether a borrower is restricted from new borrowing. * * @param borrower The borrower to check. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestrictedForBorrower( address borrower ) external view returns (bool) { return _BORROWER_RESTRICTIONS_[borrower]; } /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (LS1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * Other changes which could affect borrowers' repayment plans are also restricted during * this period. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get information about a shortfall that occurred. * * @param shortfallCounter The array index for the shortfall event to look up. * * @return Struct containing the epoch and shortfall index value. */ function getShortfall( uint256 shortfallCounter ) external view returns (LS1Types.Shortfall memory) { return _SHORTFALLS_[shortfallCounter]; } /** * @notice Get the number of shortfalls that have occurred. * * @return The number of shortfalls that have occurred. */ function getShortfallCount() external view returns (uint256) { return _SHORTFALLS_.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 // // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { LS1Admin } from './impl/LS1Admin.sol'; import { LS1Borrowing } from './impl/LS1Borrowing.sol'; import { LS1DebtAccounting } from './impl/LS1DebtAccounting.sol'; import { LS1ERC20 } from './impl/LS1ERC20.sol'; import { LS1Failsafe } from './impl/LS1Failsafe.sol'; import { LS1Getters } from './impl/LS1Getters.sol'; import { LS1Operators } from './impl/LS1Operators.sol'; /** * @title LiquidityStakingV1 * @author dYdX * * @notice Contract for staking tokens, which may then be borrowed by pre-approved borrowers. * * NOTE: Most functions will revert if epoch zero has not started. */ contract LiquidityStakingV1 is LS1Borrowing, LS1DebtAccounting, LS1Admin, LS1Operators, LS1Getters, LS1Failsafe { // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Borrowing(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ function initialize( uint256 interval, uint256 offset, uint256 blackoutWindow ) external initializer { __LS1Roles_init(); __LS1EpochSchedule_init(interval, offset, blackoutWindow); __LS1Rewards_init(); __LS1BorrowerAllocations_init(); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @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.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Borrowing } from './LS1Borrowing.sol'; /** * @title LS1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract LS1Admin is LS1Borrowing { using SafeCast for uint256; using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * Reverts if the new interval is less than twice the blackout window. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require(block.timestamp < offset, 'LS1Admin: Started epoch zero'); _setEpochParameters(interval, offset); return; } // Require that we are not currently in a blackout window. require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require(originalCurrentEpoch == newCurrentEpoch, 'LS1Admin: Changed epochs'); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBlackoutWindow(blackoutWindow); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } /** * @notice Change the allocations of certain borrowers. Can be used to add and remove borrowers. * Increases take effect in the next epoch, but decreases will restrict borrowing immediately. * This function cannot be called during the blackout window. * * @param borrowers Array of borrower addresses. * @param newAllocations Array of new allocations per borrower, as hundredths of a percent. */ function setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { require(borrowers.length == newAllocations.length, 'LS1Admin: Params length mismatch'); require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBorrowerAllocations(borrowers, newAllocations); } function setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { _setBorrowingRestriction(borrower, isBorrowingRestricted); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Borrowing * @author dYdX * * @dev External functions for borrowers. See LS1BorrowerAllocations for details on * borrower accounting. */ abstract contract LS1Borrowing is LS1Staking, LS1BorrowerAllocations { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Borrowed( address indexed borrower, uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( address indexed borrower, address sender, uint256 amount, uint256 newBorrowedBalance ); event RepaidDebt( address indexed borrower, address sender, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Borrow staked funds. * * @param amount The token amount to borrow. */ function borrow( uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot borrow zero'); address borrower = msg.sender; // Revert if the borrower is restricted. require(!_BORROWER_RESTRICTIONS_[borrower], 'LS1Borrowing: Restricted'); // Get contract available amount and revert if there is not enough to withdraw. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); require( amount <= totalAvailableForBorrow, 'LS1Borrowing: Amount > available' ); // Get new net borrow and revert if it is greater than the allocated balance for new borrowing. uint256 newBorrowedBalance = _BORROWED_BALANCES_[borrower].add(amount); require( newBorrowedBalance <= _getAllocatedBalanceForNewBorrowing(borrower), 'LS1Borrowing: Amount > allocated' ); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.add(amount); // Transfer token to the borrower. STAKED_TOKEN.safeTransfer(borrower, amount); emit Borrowed(borrower, amount, newBorrowedBalance); } /** * @notice Repay borrowed funds for the specified borrower. Reverts if repay amount exceeds * borrowed amount. * * @param borrower The borrower on whose behalf to make a repayment. * @param amount The amount to repay. */ function repayBorrow( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; require(amount <= oldBorrowedBalance, 'LS1Borrowing: Repay > borrowed'); uint256 newBorrowedBalance = oldBorrowedBalance.sub(amount); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidBorrow(borrower, msg.sender, amount, newBorrowedBalance); } /** * @notice Repay a debt amount owed by a borrower. * * @param borrower The borrower whose debt to repay. * @param amount The amount to repay. */ function repayDebt( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldDebtAmount = _BORROWER_DEBT_BALANCES_[borrower]; require(amount <= oldDebtAmount, 'LS1Borrowing: Repay > debt'); uint256 newDebtBalance = oldDebtAmount.sub(amount); // Update storage. _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_.add(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidDebt(borrower, msg.sender, amount, newDebtBalance); } /** * @notice Get the max additional amount that the borrower can borrow. * * @return The max additional amount that the borrower can borrow right now. */ function getBorrowableAmount( address borrower ) external view returns (uint256) { if (_BORROWER_RESTRICTIONS_[borrower]) { return 0; } // Get the remaining unused allocation for the borrower. uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; uint256 borrowerAllocatedBalance = _getAllocatedBalanceForNewBorrowing(borrower); if (borrowerAllocatedBalance <= oldBorrowedBalance) { return 0; } uint256 borrowerRemainingAllocatedBalance = borrowerAllocatedBalance.sub(oldBorrowedBalance); // Don't allow new borrowing to take out funds that are reserved for debt or inactive balances. // Typically, this will not be the limiting factor, but it can be. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); return Math.min(borrowerRemainingAllocatedBalance, totalAvailableForBorrow); } // ============ Public Functions ============ /** * @notice Get the funds currently available in the contract for borrowing. * * @return The amount of non-debt, non-inactive funds in the contract. */ function getContractBalanceAvailableToBorrow() public view returns (uint256) { uint256 availableStake = getContractBalanceAvailableToWithdraw(); uint256 inactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Note: The funds available to withdraw may be less than the inactive balance. if (availableStake <= inactiveBalance) { return 0; } return availableStake.sub(inactiveBalance); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; /** * @title LS1DebtAccounting * @author dYdX * * @dev Allows converting an overdue balance into "debt", which is accounted for separately from * the staked and borrowed balances. This allows the system to rebalance/restabilize itself in the * case where a borrower fails to return borrowed funds on time. * * The shortfall debt calculation is as follows: * * - Let A be the total active balance. * - Let B be the total borrowed balance. * - Let X be the total inactive balance. * - Then, a shortfall occurs if at any point B > A. * - The shortfall debt amount is `D = B - A` * - The borrowed balances are decreased by `B_new = B - D` * - The inactive balances are decreased by `X_new = X - D` * - The shortfall index is recorded as `Y = X_new / X` * - The borrower and staker debt balances are increased by `D` * * Note that `A + X >= B` (The active and inactive balances are at least the borrowed balance.) * This implies that `X >= D` (The inactive balance is always at least the shortfall debt.) */ abstract contract LS1DebtAccounting is LS1BorrowerAllocations { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; // ============ Events ============ event ConvertedInactiveBalancesToDebt( uint256 shortfallAmount, uint256 shortfallIndex, uint256 newInactiveBalance ); event DebtMarked( address indexed borrower, uint256 amount, uint256 newBorrowedBalance, uint256 newDebtBalance ); // ============ External Functions ============ /** * @notice Restrict a borrower from borrowing. The borrower must have exceeded their borrowing * allocation. Can be called by anyone. * * Unlike markDebt(), this function can be called even if the contract in TOTAL is not insolvent. */ function restrictBorrower( address borrower ) external nonReentrant { require( isBorrowerOverdue(borrower), 'LS1DebtAccounting: Borrower not overdue' ); _setBorrowingRestriction(borrower, true); } /** * @notice Convert the shortfall amount between the active and borrowed balances into “debt.” * * The function determines the size of the debt, and then does the following: * - Assign the debt to borrowers, taking the same amount out of their borrowed balance. * - Impose borrow restrictions on borrowers to whom the debt was assigned. * - Socialize the loss pro-rata across inactive balances. Each balance with a loss receives * an equal amount of debt balance that can be withdrawn as debts are repaid. * * @param borrowers A list of borrowers who are responsible for the full shortfall amount. * * @return The shortfall debt amount. */ function markDebt( address[] calldata borrowers ) external nonReentrant returns (uint256) { // The debt is equal to the difference between the total active and total borrowed balances. uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent); // Attribute debt to borrowers. _attributeDebtToBorrowers(shortfallDebt, totalActiveCurrent, borrowers); // Apply the debt to inactive balances, moving the same amount into users debt balances. _convertInactiveBalanceToDebt(shortfallDebt); return shortfallDebt; } // ============ Public Functions ============ /** * @notice Whether the borrower is overdue on a payment, and is currently subject to having their * borrowing rights revoked. * * @param borrower The borrower to check. */ function isBorrowerOverdue( address borrower ) public view returns (bool) { uint256 allocatedBalance = getAllocatedBalanceCurrentEpoch(borrower); uint256 borrowedBalance = _BORROWED_BALANCES_[borrower]; return borrowedBalance > allocatedBalance; } // ============ Private Functions ============ /** * @dev Helper function to partially or fully convert inactive balances to debt. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. */ function _convertInactiveBalanceToDebt( uint256 shortfallDebt ) private { // Get the total inactive balance. uint256 oldInactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Calculate the index factor for the shortfall. uint256 newInactiveBalance = 0; uint256 shortfallIndex = 0; if (oldInactiveBalance > shortfallDebt) { newInactiveBalance = oldInactiveBalance.sub(shortfallDebt); shortfallIndex = SHORTFALL_INDEX_BASE.mul(newInactiveBalance).div(oldInactiveBalance); } // Get the shortfall amount applied to inactive balances. uint256 shortfallAmount = oldInactiveBalance.sub(newInactiveBalance); // Apply the loss. This moves the debt from stakers' inactive balances to their debt balances. _applyShortfall(shortfallAmount, shortfallIndex); emit ConvertedInactiveBalancesToDebt(shortfallAmount, shortfallIndex, newInactiveBalance); } /** * @dev Helper function to attribute debt to borrowers, adding it to their debt balances. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. * @param totalActiveCurrent The total active balance for the current epoch. * @param borrowers A list of borrowers responsible for the full shortfall amount. */ function _attributeDebtToBorrowers( uint256 shortfallDebt, uint256 totalActiveCurrent, address[] calldata borrowers ) private { // Find borrowers to attribute the total debt amount to. The sum of all borrower shortfalls is // always at least equal to the overall shortfall, so it is always possible to specify a list // of borrowers whose excess borrows cover the full shortfall amount. // // Denominate values in “points” scaled by TOTAL_ALLOCATION to avoid rounding. uint256 debtToBeAttributedPoints = shortfallDebt.mul(TOTAL_ALLOCATION); uint256 shortfallDebtAfterRounding = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 borrowedBalanceTokenAmount = _BORROWED_BALANCES_[borrower]; uint256 borrowedBalancePoints = borrowedBalanceTokenAmount.mul(TOTAL_ALLOCATION); uint256 allocationPoints = getAllocationFractionCurrentEpoch(borrower); uint256 allocatedBalancePoints = totalActiveCurrent.mul(allocationPoints); // Skip this borrower if they have not exceeded their allocation. if (borrowedBalancePoints <= allocatedBalancePoints) { continue; } // Calculate the borrower's debt, and limit to the remaining amount to be allocated. uint256 borrowerDebtPoints = borrowedBalancePoints.sub(allocatedBalancePoints); borrowerDebtPoints = Math.min(borrowerDebtPoints, debtToBeAttributedPoints); // Move the debt from the borrowers' borrowed balance to the debt balance. Rounding may occur // when converting from “points” to tokens. We round up to ensure the final borrowed balance // is not greater than the allocated balance. uint256 borrowerDebtTokenAmount = borrowerDebtPoints.divRoundUp(TOTAL_ALLOCATION); uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].add(borrowerDebtTokenAmount); uint256 newBorrowedBalance = borrowedBalanceTokenAmount.sub(borrowerDebtTokenAmount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _BORROWED_BALANCES_[borrower] = newBorrowedBalance; emit DebtMarked(borrower, borrowerDebtTokenAmount, newBorrowedBalance, newDebtBalance); shortfallDebtAfterRounding = shortfallDebtAfterRounding.add(borrowerDebtTokenAmount); // Restrict the borrower from further borrowing. _setBorrowingRestriction(borrower, true); // Update the remaining amount to allocate. debtToBeAttributedPoints = debtToBeAttributedPoints.sub(borrowerDebtPoints); // Exit early if all debt was allocated. if (debtToBeAttributedPoints == 0) { break; } } // Require the borrowers to cover the full debt amount. This should always be possible. require( debtToBeAttributedPoints == 0, 'LS1DebtAccounting: Borrowers do not cover the shortfall' ); // Move the debt from the total borrowed balance to the total debt balance. _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(shortfallDebtAfterRounding); _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.add(shortfallDebtAfterRounding); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Allows a user with an active stake to transfer their * staked tokens to another user, even if they would otherwise be restricted from withdrawing. */ abstract contract LS1ERC20 is LS1StakedBalances, IERC20Detailed { using SafeMath for uint256; // ============ External Functions ============ function name() external pure override returns (string memory) { return 'dYdX Staked USDC'; } function symbol() external pure override returns (string memory) { return 'stkUSDC'; } function decimals() external pure override returns (uint8) { return 6; } /** * @notice Get the total supply of `STAKED_TOKEN` staked to the contract. * This value is calculated from adding the active + inactive balances of * this current epoch. * * @return The total staked balance of this contract. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get the current balance of `STAKED_TOKEN` the user has staked to the contract. * This value includes the users active + inactive balances, but note that only * their active balance in the next epoch is transferable. * * @param account The account to get the balance of. * * @return The user's balance. */ function balanceOf( address account ) external view override returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'LS1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'LS1ERC20: Decreased allowance below zero' ) ); return true; } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'LS1ERC20: Transfer from address(0)'); require(recipient != address(0), 'LS1ERC20: Transfer to address(0)'); require( getTransferableBalance(sender) >= amount, 'LS1ERC20: Transfer exceeds next epoch active balance' ); _transferCurrentAndNextActiveBalance(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'LS1ERC20: Approve from address(0)'); require(spender != address(0), 'LS1ERC20: Approve to address(0)'); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Failsafe * @author dYdX * * @dev Functions for recovering from very unlikely edge cases. */ abstract contract LS1Failsafe is LS1StakedBalances { using SafeCast for uint256; using SafeMath for uint256; /** * @notice Settle the sender's inactive balance up to the specified epoch. This allows the * balance to be settled while putting an upper bound on the gas expenditure per function call. * This is unlikely to be needed in practice. * * @param maxEpoch The epoch to settle the sender's inactive balance up to. */ function failsafeSettleUserInactiveBalanceToEpoch( uint256 maxEpoch ) external nonReentrant { address staker = msg.sender; _failsafeSettleUserInactiveBalance(staker, maxEpoch); } /** * @notice Sets the sender's inactive balance to zero. This allows for recovery from a situation * where the gas cost to settle the balance is higher than the value of the balance itself. * We provide this function as an alternative to settlement, since the gas cost for settling an * inactive balance is unbounded (except in that it may grow at most linearly with the number of * epochs that have passed). */ function failsafeDeleteUserInactiveBalance() external nonReentrant { address staker = msg.sender; _failsafeDeleteUserInactiveBalance(staker); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are three types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. * * DEBT_OPERATOR_ROLE: * * This operator is allowed to decrease staker and borrower debt balances. Typically, each change * to a staker debt balance should be offset by a corresponding change in a borrower debt * balance, but this is not strictly required. This role could used by a smart contract to * tokenize debt balances or to provide a pro-rata distribution to debt holders, for example. */ abstract contract LS1Operators is LS1Staking { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); event OperatorDecreasedStakerDebt( address indexed staker, uint256 amount, uint256 newDebtBalance, address operator ); event OperatorDecreasedBorrowerDebt( address indexed borrower, uint256 amount, uint256 newDebtBalance, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, amount); emit OperatorWithdrawalRequestedFor(staker, amount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, amount); emit OperatorWithdrewStakeFor(staker, recipient, amount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } /** * @notice Decreased the balance recording debt owed to a staker. * * @param staker The staker whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseStakerDebt( address staker, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); uint256 newDebtBalance = oldDebtBalance.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit OperatorDecreasedStakerDebt(staker, amount, newDebtBalance, msg.sender); return newDebtBalance; } /** * @notice Decreased the balance recording debt owed by a borrower. * * @param borrower The borrower whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseBorrowerDebt( address borrower, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].sub(amount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); emit OperatorDecreasedBorrowerDebt(borrower, amount, newDebtBalance, msg.sender); return newDebtBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title SafeCast * @author dYdX * * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require(uint256(b) == a, 'SafeCast: toUint16 overflow'); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require(uint256(b) == a, 'SafeCast: toUint32 overflow'); return b; } /** * @dev Downcast to a uint112, reverting on overflow. */ function toUint112( uint256 a ) internal pure returns (uint112) { uint112 b = uint112(a); require(uint256(b) == a, 'SafeCast: toUint112 overflow'); return b; } /** * @dev Downcast to a uint120, reverting on overflow. */ function toUint120( uint256 a ) internal pure returns (uint120) { uint120 b = uint120(a); require(uint256(b) == a, 'SafeCast: toUint120 overflow'); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require(uint256(b) == a, 'SafeCast: toUint224 overflow'); return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } 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'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1BorrowerAllocations * @author dYdX * * @dev Gives a set of addresses permission to withdraw staked funds. * * The amount that can be withdrawn depends on a borrower's allocation percentage and the total * available funds. Both the allocated percentage and total available funds can change, at * predefined times specified by LS1EpochSchedule. * * If a borrower's borrowed balance is greater than their allocation at the start of the next epoch * then they are expected and trusted to return the difference before the start of that epoch. */ abstract contract LS1BorrowerAllocations is LS1StakedBalances { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The total units to be allocated. uint256 public constant TOTAL_ALLOCATION = 1e4; // ============ Events ============ event ScheduledBorrowerAllocationChange( address indexed borrower, uint256 oldAllocation, uint256 newAllocation, uint256 epochNumber ); event BorrowingRestrictionChanged( address indexed borrower, bool isBorrowingRestricted ); // ============ Initializer ============ function __LS1BorrowerAllocations_init() internal { _BORROWER_ALLOCATIONS_[address(0)] = LS1Types.StoredAllocation({ currentEpoch: 0, currentEpochAllocation: TOTAL_ALLOCATION.toUint120(), nextEpochAllocation: TOTAL_ALLOCATION.toUint120() }); } // ============ Public Functions ============ /** * @notice Get the borrower allocation for the current epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's current allocation in hundreds of a percent. */ function getAllocationFractionCurrentEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).currentEpochAllocation); } /** * @notice Get the borrower allocation for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's next allocation in hundreds of a percent. */ function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); } /** * @notice Get the allocated borrowable token balance of a borrower for the current epoch. * * This is the amount which a borrower can be penalized for exceeding. * * @param borrower The borrower to get the allocation for. * * @return The token amount allocated to the borrower for the current epoch. */ function getAllocatedBalanceCurrentEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionCurrentEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceCurrentEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } /** * @notice Preview the allocated balance of a borrower for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The anticipated token amount allocated to the borrower for the next epoch. */ function getAllocatedBalanceNextEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionNextEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceNextEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Internal Functions ============ /** * @dev Change the allocations of certain borrowers. */ function _setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) internal { // These must net out so that the total allocation is unchanged. uint256 oldAllocationSum = 0; uint256 newAllocationSum = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 newAllocation = newAllocations[i]; // Get the old allocation. LS1Types.StoredAllocation memory allocationStruct = _loadBorrowerAllocation(borrower); uint256 oldAllocation = uint256(allocationStruct.currentEpochAllocation); // Update the borrower's next allocation. allocationStruct.nextEpochAllocation = newAllocation.toUint120(); // If epoch zero hasn't started, update current allocation as well. uint256 epochNumber = 0; if (hasEpochZeroStarted()) { epochNumber = uint256(allocationStruct.currentEpoch).add(1); } else { allocationStruct.currentEpochAllocation = newAllocation.toUint120(); } // Commit the new allocation. _BORROWER_ALLOCATIONS_[borrower] = allocationStruct; emit ScheduledBorrowerAllocationChange(borrower, oldAllocation, newAllocation, epochNumber); // Record totals. oldAllocationSum = oldAllocationSum.add(oldAllocation); newAllocationSum = newAllocationSum.add(newAllocation); } // Require the total allocated units to be unchanged. require( oldAllocationSum == newAllocationSum, 'LS1BorrowerAllocations: Invalid' ); } /** * @dev Restrict a borrower from further borrowing. */ function _setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) internal { bool oldIsBorrowingRestricted = _BORROWER_RESTRICTIONS_[borrower]; if (oldIsBorrowingRestricted != isBorrowingRestricted) { _BORROWER_RESTRICTIONS_[borrower] = isBorrowingRestricted; emit BorrowingRestrictionChanged(borrower, isBorrowingRestricted); } } /** * @dev Get the allocated balance that the borrower can make use of for new borrowing. * * @return The amount that the borrower can borrow up to. */ function _getAllocatedBalanceForNewBorrowing( address borrower ) internal view returns (uint256) { // Use the smaller of the current and next allocation fractions, since if a borrower's // allocation was just decreased, we should take that into account in limiting new borrows. uint256 currentAllocation = getAllocationFractionCurrentEpoch(borrower); uint256 nextAllocation = getAllocationFractionNextEpoch(borrower); uint256 allocation = Math.min(currentAllocation, nextAllocation); // If we are in the blackout window, use the next active balance. Otherwise, use current. // Note that the next active balance is never greater than the current active balance. uint256 availableTokens; if (inBlackoutWindow()) { availableTokens = getTotalActiveBalanceNextEpoch(); } else { availableTokens = getTotalActiveBalanceCurrentEpoch(); } return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Private Functions ============ function _loadBorrowerAllocation( address borrower ) private view returns (LS1Types.StoredAllocation memory) { LS1Types.StoredAllocation memory allocation = _BORROWER_ALLOCATIONS_[borrower]; // Ignore rollover logic before epoch zero. if (hasEpochZeroStarted()) { uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(allocation.currentEpoch)) { // Roll the allocation forward. allocation.currentEpoch = currentEpoch.toUint16(); allocation.currentEpochAllocation = allocation.nextEpochAllocation; } } return allocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1ERC20 } from './LS1ERC20.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Staking * @author dYdX * * @dev External functions for stakers. See LS1StakedBalances for details on staker accounting. */ abstract contract LS1Staking is LS1StakedBalances, LS1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 amount ); event WithdrawalRequested( address indexed staker, uint256 amount ); event WithdrewStake( address indexed staker, address recipient, uint256 amount ); event WithdrewDebt( address indexed staker, address recipient, uint256 amount, uint256 newDebtBalance ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param amount The amount to stake. */ function stake( uint256 amount ) external nonReentrant { _stake(msg.sender, amount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param amount The amount to stake. */ function stakeFor( address staker, uint256 amount ) external nonReentrant { _stake(staker, amount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawal( uint256 amount ) external nonReentrant { _requestWithdrawal(msg.sender, amount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 amount ) external nonReentrant { _withdrawStake(msg.sender, recipient, amount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, amount); return amount; } /** * @notice Withdraw a debt amount owed to the sender, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The token amount to withdraw from the sender's debt balance. */ function withdrawDebt( address recipient, uint256 amount ) external nonReentrant { _withdrawDebt(msg.sender, recipient, amount); } /** * @notice Withdraw the max available debt amount. * * This is less gas-efficient than querying the max via eth_call and calling withdrawDebt(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxDebt( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getDebtAvailableToWithdraw(msg.sender); _withdrawDebt(msg.sender, recipient, amount); return amount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available to withdraw taking into account the contract balance. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. uint256 stakerBalance = getInactiveBalanceCurrentEpoch(staker); uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); return Math.min(stakerBalance, totalStakeAvailable); } /** * @notice Get the funds currently available in the contract for staker withdrawals. * * @return The amount of non-debt funds in the contract. */ function getContractBalanceAvailableToWithdraw() public view returns (uint256) { uint256 contractBalance = STAKED_TOKEN.balanceOf(address(this)); uint256 availableDebtBalance = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return contractBalance.sub(availableDebtBalance); // Should never underflow. } /** * @notice Get the amount of debt available to withdraw. * * @param staker The address whose balance to check. * * @return The debt amount that can be withdrawn. */ function getDebtAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that `totalDebtAvailable` should never be less than the contract token balance. uint256 stakerDebtBalance = getStakerDebtBalance(staker); uint256 totalDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return Math.min(stakerDebtBalance, totalDebtAvailable); } // ============ Internal Functions ============ function _stake( address staker, uint256 amount ) internal { // Increase current and next active balance. _increaseCurrentAndNextActiveBalance(staker, amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit Staked(staker, msg.sender, amount); emit Transfer(address(0), msg.sender, amount); } function _requestWithdrawal( address staker, uint256 amount ) internal { require( !inBlackoutWindow(), 'LS1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( amount <= requestableBalance, 'LS1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, amount); emit WithdrawalRequested(staker, amount); } function _withdrawStake( address staker, address recipient, uint256 amount ) internal { // Get contract available amount and revert if there is not enough to withdraw. uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); require( amount <= totalStakeAvailable, 'LS1Staking: Withdraw exceeds amount available in the contract' ); // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( amount <= withdrawableBalance, 'LS1Staking: Withdraw exceeds inactive balance' ); // Decrease the staker's current and next inactive balance. Reverts if balance is insufficient. _decreaseCurrentAndNextInactiveBalance(staker, amount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit Transfer(msg.sender, address(0), amount); emit WithdrewStake(staker, recipient, amount); } // ============ Private Functions ============ function _withdrawDebt( address staker, address recipient, uint256 amount ) private { // Get old amounts and revert if there is not enough to withdraw. uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); // Caculate updated amounts and update storage. uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.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 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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Rewards } from './LS1Rewards.sol'; /** * @title LS1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Internal functions may revert if epoch zero has not started. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Available for borrowing; earning staking rewards; cannot be withdrawn by staker. * - inactive: Unavailable for borrowing; does not earn rewards; can be withdrawn by the staker. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. Also, inactive user balances make use of the shortfallCounter field as * described below. * * INACTIVE BALANCE ACCOUNTING: * * Inactive funds may be subject to pro-rata socialized losses in the event of a shortfall where * a borrower is late to pay back funds that have been requested for withdrawal. We track losses * via indexes. Each index represents the fraction of inactive funds that were converted into * debt during a given shortfall event. Each staker inactive balance stores a cached shortfall * counter, representing the number of shortfalls that occurred in the past relative to when the * balance was last updated. * * Any losses incurred by an inactive balance translate into an equal credit to that staker's * debt balance. See LS1DebtAccounting for more info about how the index is calculated. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via LS1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards or debt balances. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract LS1StakedBalances is LS1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 internal constant SHORTFALL_INDEX_BASE = 1e36; // ============ Events ============ event ReceivedDebt( address indexed staker, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get a staker's debt balance, after accounting for unsettled shortfalls. * Note that this does not modify _STAKER_DEBT_BALANCES_, so the debt balance must still be * settled before it can be withdrawn. * * @param staker The staker to get the balance of. * * @return The settled debt balance. */ function getStakerDebtBalance( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (, uint256 newDebtAmount) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return _STAKER_DEBT_BALANCES_[staker].add(newDebtAmount); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleStakerDebtBalance( address staker ) internal returns (uint256) { // Settle the inactive balance to settle any new debt. _settleBalance(staker, false); // Return the settled debt balance. return _STAKER_DEBT_BALANCES_[staker]; } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } function _applyShortfall( uint256 shortfallAmount, uint256 shortfallIndex ) internal { // Decrease the total inactive balance. _decreaseCurrentAndNextBalances(address(0), false, shortfallAmount); _SHORTFALLS_.push(LS1Types.Shortfall({ epoch: getCurrentEpoch().toUint16(), index: shortfallIndex.toUint224() })); } /** * @dev Does the same thing as _settleBalance() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeSettleUserInactiveBalance( address staker, uint256 maxEpoch ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = _failsafeLoadUserInactiveBalanceForUpdate(balancePtr, staker, maxEpoch); _storeBalance(balancePtr, balance); } /** * @dev Sets the user inactive balance to zero. See LS1Failsafe. * * Since the balance will never be settled, the staker loses any debt balance that they would * have otherwise been entitled to from shortfall losses. * * Also note that we don't update the total inactive balance, but this is fine. */ function _failsafeDeleteUserInactiveBalance( address staker ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = LS1Types.StoredBalance({ currentEpoch: 0, currentEpochBalance: 0, nextEpochBalance: 0, shortfallCounter: 0 }); _storeBalance(balancePtr, balance); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (LS1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function modifies state, and so the balance MUST be stored afterwards. * - For active balances: if a rollover occurs, rewards are settled to the epoch boundary. * - For inactive user balances: if a shortfall occurs, the user's debt balance is increased. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (LS1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( LS1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Total inactive balance. if (maybeStaker == address(0)) { return _loadTotalInactiveBalance(balancePtr); } // User inactive balance. (LS1Types.StoredBalance memory balance, uint256 newStakerDebt) = _loadUserInactiveBalance(balancePtr); if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[maybeStaker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[maybeStaker] = newDebtBalance; emit ReceivedDebt(maybeStaker, newStakerDebt, newDebtBalance); } return balance; } function _loadActiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns ( LS1Types.StoredBalance memory, uint256, uint256, bool ) { LS1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadTotalInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } function _loadUserInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory, uint256) { LS1Types.StoredBalance memory balance = balancePtr; uint256 currentEpoch = getCurrentEpoch(); // If there is no non-zero balance, sync the epoch number and shortfall counter and exit. // Note: Next inactive balance is always >= current, so we only need to check next. if (balance.nextEpochBalance == 0) { balance.currentEpoch = currentEpoch.toUint16(); balance.shortfallCounter = _SHORTFALLS_.length.toUint16(); return (balance, 0); } // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } return (balance, newStakerDebt); } function _applyShortfallsToBalance( LS1Types.StoredBalance memory balance ) private view returns (LS1Types.StoredBalance memory, uint256) { // Get the cached and global shortfall counters. uint256 shortfallCounter = uint256(balance.shortfallCounter); uint256 globalShortfallCounter = _SHORTFALLS_.length; // If the counters are in sync, then there is nothing to do. if (shortfallCounter == globalShortfallCounter) { return (balance, 0); } // Get the balance params. uint16 cachedEpoch = balance.currentEpoch; uint256 oldCurrentBalance = uint256(balance.currentEpochBalance); // Calculate the new balance after applying shortfalls. // // Note: In theory, this while-loop may render an account's funds inaccessible if there are // too many shortfalls, and too much gas is required to apply them all. This is very unlikely // to occur in practice, but we provide _failsafeLoadUserInactiveBalance() just in case to // ensure recovery is possible. uint256 newCurrentBalance = oldCurrentBalance; while (shortfallCounter < globalShortfallCounter) { LS1Types.Shortfall memory shortfall = _SHORTFALLS_[shortfallCounter]; // Stop applying shortfalls if they are in the future relative to the balance current epoch. if (shortfall.epoch > cachedEpoch) { break; } // Update the current balance to reflect the shortfall. uint256 shortfallIndex = uint256(shortfall.index); newCurrentBalance = newCurrentBalance.mul(shortfallIndex).div(SHORTFALL_INDEX_BASE); // Increment the staker's shortfall counter. shortfallCounter = shortfallCounter.add(1); } // Calculate the loss. // If the loaded balance is stored, this amount must be added to the staker's debt balance. uint256 newStakerDebt = oldCurrentBalance.sub(newCurrentBalance); // Update the balance. balance.currentEpochBalance = newCurrentBalance.toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(newStakerDebt).toUint112(); balance.shortfallCounter = shortfallCounter.toUint16(); return (balance, newStakerDebt); } /** * @dev Store a balance. */ function _storeBalance( LS1Types.StoredBalance storage balancePtr, LS1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; balancePtr.shortfallCounter = balance.shortfallCounter; } /** * @dev Does the same thing as _loadBalanceForUpdate() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeLoadUserInactiveBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address staker, uint256 maxEpoch ) private returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Validate maxEpoch. uint256 currentEpoch = getCurrentEpoch(); uint256 cachedEpoch = uint256(balance.currentEpoch); require( maxEpoch >= cachedEpoch && maxEpoch <= currentEpoch, 'LS1StakedBalances: maxEpoch' ); // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (maxEpoch > cachedEpoch) { balance.currentEpoch = maxEpoch.toUint16(); // Use maxEpoch instead of currentEpoch. balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } // Apply debt if needed. if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[staker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit ReceivedDebt(staker, newStakerDebt, newDebtBalance); } return balance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1EpochSchedule } from './LS1EpochSchedule.sol'; /** * @title LS1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract LS1Rewards is LS1EpochSchedule { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require(distributionEnd >= distributionStart, 'LS1Rewards: Invalid parameters'); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __LS1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Roles } from './LS1Roles.sol'; /** * @title LS1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract LS1EpochSchedule is LS1Roles { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Minimum blackout window. Note: The min epoch length is twice the current blackout window. uint256 private constant MIN_BLACKOUT_WINDOW = 3 days; /// @dev Maximum epoch length. Note: The max blackout window is half the current epoch length. uint256 private constant MAX_EPOCH_LENGTH = 92 days; // Approximately one quarter year. // ============ Events ============ event EpochParametersChanged( LS1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __LS1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'LS1EpochSchedule: Epoch zero must be in future' ); // Don't use _setBlackoutWindow() since the interval is not set yet and validation would fail. _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { _validateParamLengths(interval, _BLACKOUT_WINDOW_); LS1Types.EpochParameters memory epochParameters = LS1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _validateParamLengths(uint256(_EPOCH_PARAMETERS_.interval), blackoutWindow); _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The length of an epoch, in seconds. * @return The start of epoch zero, in seconds. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(block.timestamp >= offset, 'LS1EpochSchedule: Epoch zero has not started'); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } /** * @dev Helper for common validation: verify that the interval and window lengths are valid. */ function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Roles * @author dYdX * * @dev Defines roles used in the LiquidityStakingV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove users from any of the below roles it manages. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- BORROWER_ADMIN_ROLE * | -> May set borrower allocations and allow/restrict borrowers from borrowing. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * | -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). * | * +-- DEBT_OPERATOR_ROLE * -> May decrease borrow debt and decrease staker debt. */ abstract contract LS1Roles is LS1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant BORROWER_ADMIN_ROLE = keccak256('BORROWER_ADMIN_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); bytes32 public constant DEBT_OPERATOR_ROLE = keccak256('DEBT_OPERATOR_ROLE'); function __LS1Roles_init() internal { // Assign roles to the sender. // // The DEBT_OPERATOR_ROLE, STAKE_OPERATOR_ROLE, and CLAIM_OPERATOR_ROLE roles are not // initially assigned. These can be assigned to other smart contracts to provide additional // functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); _setupRole(BORROWER_ADMIN_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(DEBT_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Update the balance.
balance.currentEpochBalance = newCurrentBalance.toUint112();
5,860,584
[ 1, 1891, 326, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 11013, 18, 2972, 14638, 13937, 273, 394, 3935, 13937, 18, 869, 5487, 17666, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/hop/l2/HopImplL2.sol
@notice Struct to be used in decode step from input parameter - a specific case of bridging after swap. @dev the data being encoded in offchain or by caller should have values set in this sequence of properties in this struct The address receiving funds at the destination AMM address of Hop on L2 The chainId of the destination chain fees passed to relayer The minimum amount received after attempting to swap in the destination AMM market. 0 if no swap is intended. The deadline for swapping in the destination AMM market. 0 if no swap is intended. Minimum amount expected to be received or bridged to destination deadline for bridging to destination socket offchain created hash
struct HopBridgeDataNoToken { address receiverAddress; address hopAMM; uint256 toChainId; uint256 bonderFee; uint256 amountOutMin; uint256 deadline; uint256 amountOutMinDestination; uint256 deadlineDestination; bytes32 metadata; }
11,003,499
[ 1, 3823, 358, 506, 1399, 316, 2495, 2235, 628, 810, 1569, 300, 279, 2923, 648, 434, 324, 1691, 1998, 1839, 7720, 18, 225, 326, 501, 3832, 3749, 316, 3397, 5639, 578, 635, 4894, 1410, 1240, 924, 444, 316, 333, 3102, 434, 1790, 316, 333, 1958, 1021, 1758, 15847, 284, 19156, 622, 326, 2929, 432, 8206, 1758, 434, 670, 556, 603, 511, 22, 1021, 2687, 548, 434, 326, 2929, 2687, 1656, 281, 2275, 358, 1279, 1773, 1021, 5224, 3844, 5079, 1839, 15600, 358, 7720, 316, 326, 2929, 432, 8206, 13667, 18, 374, 309, 1158, 7720, 353, 12613, 18, 1021, 14096, 364, 7720, 1382, 316, 326, 2929, 432, 8206, 13667, 18, 374, 309, 1158, 7720, 353, 12613, 18, 23456, 3844, 2665, 358, 506, 5079, 578, 324, 1691, 2423, 358, 2929, 14096, 364, 324, 1691, 1998, 358, 2929, 2987, 3397, 5639, 2522, 1651, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 670, 556, 13691, 751, 2279, 1345, 288, 203, 3639, 1758, 5971, 1887, 31, 203, 3639, 1758, 19055, 2192, 49, 31, 203, 3639, 2254, 5034, 358, 3893, 548, 31, 203, 3639, 2254, 5034, 324, 265, 765, 14667, 31, 203, 3639, 2254, 5034, 3844, 1182, 2930, 31, 203, 3639, 2254, 5034, 14096, 31, 203, 3639, 2254, 5034, 3844, 1182, 2930, 5683, 31, 203, 3639, 2254, 5034, 14096, 5683, 31, 203, 3639, 1731, 1578, 1982, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /* * Zethroll. * * Adapted from PHXRoll, written in March 2018 by TechnicalRise: * https://www.reddit.com/user/TechnicalRise/ * * Adapted for Zethr by Norsefire and oguzhanox. * * Gas golfed by Etherguy * Audited & commented by Klob */ contract ZTHReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); } contract ZTHInterface { function getFrontEndTokenBalanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool); function approve(address spender, uint tokens) public returns (bool); } contract Zethroll is ZTHReceivingContract { using SafeMath for uint; // Makes sure that player profit can't exceed a maximum amount, // that the bet size is valid, and the playerNumber is in range. modifier betIsValid(uint _betSize, uint _playerNumber) { require( calculateProfit(_betSize, _playerNumber) < maxProfit && _betSize >= minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; } // Requires game to be currently active modifier gameIsActive { require(gamePaused == false); _; } // Requires msg.sender to be owner modifier onlyOwner { require(msg.sender == owner); _; } // Constants uint constant private MAX_INT = 2 ** 256 - 1; uint constant public maxProfitDivisor = 1000000; uint constant public maxNumber = 99; uint constant public minNumber = 2; uint constant public houseEdgeDivisor = 1000; // Configurables bool public gamePaused; address public owner; address public ZethrBankroll; address public ZTHTKNADDR; ZTHInterface public ZTHTKN; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet = 0; // Trackers uint public totalBets; uint public totalZTHWagered; // Events // Logs bets + output to web3 for precise 'payout on win' field in UI event LogBet(address sender, uint value, uint rollUnder); // Outputs to web3 UI on bet result // Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); // Logs owner transfers event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); // Logs changes in maximum profit event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); // Logs current contract balance event CurrentContractBalance(uint _tokens); constructor (address zthtknaddr, address zthbankrolladdr) public { // Owner is deployer owner = msg.sender; // Initialize the ZTH contract and bankroll interfaces ZTHTKN = ZTHInterface(zthtknaddr); ZTHTKNADDR = zthtknaddr; // Set the bankroll ZethrBankroll = zthbankrolladdr; // Init 990 = 99% (1% houseEdge) houseEdge = 990; // The maximum profit from each bet is 10% of the contract balance. ownerSetMaxProfitAsPercentOfHouse(10000); // Init min bet (1 ZTH) ownerSetMinBet(1e18); // Allow 'unlimited' token transfer by the bankroll ZTHTKN.approve(zthbankrolladdr, MAX_INT); } function() public payable {} // receive zethr dividends // Returns a random number using a specified block number // Always use a FUTURE block number. function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { return uint256(keccak256( abi.encodePacked( blockhash(blockn), entropy) )); } // Random helper function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { return maxRandom(blockn, entropy) % upper; } // Calculate the maximum potential profit function calculateProfit(uint _initBet, uint _roll) private view returns (uint) { return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; } // I present a struct which takes only 20k gas struct playerRoll{ uint200 tokenValue; // Token value in uint uint48 blockn; // Block number 48 bits uint8 rollUnder; // Roll under 8 bits } // Mapping because a player can do one roll at a time mapping(address => playerRoll) public playerRolls; function _playerRollDice(uint _rollUnder, TKN _tkn) private gameIsActive betIsValid(_tkn.value, _rollUnder) { require(_tkn.value < ((2 ** 200) - 1)); // Smaller than the storage of 1 uint200; require(block.number < ((2 ** 48) - 1)); // Current block number smaller than storage of 1 uint48 // Note that msg.sender is the Token Contract Address // and "_from" is the sender of the tokens // Check that this is a ZTH token transfer require(_zthToken(msg.sender)); playerRoll memory roll = playerRolls[_tkn.sender]; // Cannot bet twice in one block require(block.number != roll.blockn); // If there exists a roll, finish it if (roll.blockn != 0) { _finishBet(false, _tkn.sender); } // Set struct block number, token value, and rollUnder values roll.blockn = uint48(block.number); roll.tokenValue = uint200(_tkn.value); roll.rollUnder = uint8(_rollUnder); // Store the roll struct - 20k gas. playerRolls[_tkn.sender] = roll; // Provides accurate numbers for web3 and allows for manual refunds emit LogBet(_tkn.sender, _tkn.value, _rollUnder); // Increment total number of bets totalBets += 1; // Total wagered totalZTHWagered += _tkn.value; } // Finished the current bet of a player, if they have one function finishBet() public gameIsActive returns (uint) { return _finishBet(true, msg.sender); } /* * Pay winner, update contract balance * to calculate new max bet, and send reward. */ function _finishBet(bool delete_it, address target) private returns (uint){ playerRoll memory roll = playerRolls[target]; require(roll.tokenValue > 0); // No re-entracy require(roll.blockn != block.number); // If the block is more than 255 blocks old, we can't get the result // Also, if the result has already happened, fail as well uint result; if (block.number - roll.blockn > 255) { result = 1000; // Cant win } else { // Grab the result - random based ONLY on a past block (future when submitted) result = random(99, roll.blockn, target) + 1; } uint rollUnder = roll.rollUnder; if (result < rollUnder) { // Player has won! // Safely map player profit uint profit = calculateProfit(roll.tokenValue, rollUnder); if (profit > maxProfit){ profit = maxProfit; } // Safely reduce contract balance by player profit contractBalance = contractBalance.sub(profit); emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); // Update maximum profit setMaxProfit(); if (delete_it){ // Prevent re-entracy memes delete playerRolls[target]; } // Transfer profit plus original bet ZTHTKN.transfer(target, profit + roll.tokenValue); return result; } else { /* * Player has lost * Update contract balance to calculate new max bet */ emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); /* * Safely adjust contractBalance * SetMaxProfit */ contractBalance = contractBalance.add(roll.tokenValue); // No need to actually delete player roll here since player ALWAYS loses // Saves gas on next buy // Update maximum profit setMaxProfit(); return result; } } // TKN struct struct TKN {address sender; uint value;} // Token fallback to bet or deposit from bankroll function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { require(msg.sender == ZTHTKNADDR); if (_from == ZethrBankroll) { // Update the contract balance contractBalance = contractBalance.add(_value); // Update the maximum profit uint oldMaxProfit = maxProfit; setMaxProfit(); emit MaxProfitChanged(oldMaxProfit, maxProfit); return true; } else { TKN memory _tkn; _tkn.sender = _from; _tkn.value = _value; uint8 chosenNumber = uint8(_data[0]); _playerRollDice(chosenNumber, _tkn); } return true; } /* * Sets max profit */ function setMaxProfit() internal { emit CurrentContractBalance(contractBalance); maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; } // Only owner adjust contract balance variable (only used for max profit calc) function ownerUpdateContractBalance(uint newContractBalance) public onlyOwner { contractBalance = newContractBalance; } // Only owner address can set maxProfitAsPercentOfHouse function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { // Restricts each bet to a maximum profit of 20% contractBalance require(newMaxProfitAsPercent <= 200000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } // Only owner address can set minBet function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } // Only owner address can transfer ZTH function ownerTransferZTH(address sendTo, uint amount) public onlyOwner { // Safely update contract balance when sending out funds contractBalance = contractBalance.sub(amount); // update max profit setMaxProfit(); require(ZTHTKN.transfer(sendTo, amount)); emit LogOwnerTransfer(sendTo, amount); } // Only owner address can set emergency pause #1 function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } // Only owner address can set bankroll address function ownerSetBankroll(address newBankroll) public onlyOwner { ZTHTKN.approve(ZethrBankroll, 0); ZethrBankroll = newBankroll; ZTHTKN.approve(newBankroll, MAX_INT); } // Only owner address can set owner address function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } // Only owner address can selfdestruct - emergency function ownerkill() public onlyOwner { ZTHTKN.transfer(owner, contractBalance); selfdestruct(owner); } function dumpdivs() public{ ZethrBankroll.transfer(address(this).balance); } function _zthToken(address _tokenContract) private view returns (bool) { return _tokenContract == ZTHTKNADDR; // Is this the ZTH token contract? } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint 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, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
Token value in uint
uint200 tokenValue;
20,619
[ 1, 1345, 460, 316, 2254, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 6976, 1147, 620, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x55d45b21a11d3B2D77bE2D9EaD7752b74EF02ba5/sources/VinylToken.sol
* @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; }
5,082,320
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 225, 389, 2080, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 225, 389, 869, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 389, 1132, 2254, 5034, 326, 3844, 434, 2430, 358, 506, 906, 4193, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 3639, 2583, 24899, 1132, 1648, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 3639, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; 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) { // 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&#39;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 iERC223Token { function transfer(address to, uint value, bytes data) public returns (bool ok); function transferFrom(address from, address to, uint value, bytes data) public returns (bool ok); } contract ERC223Receiver { function tokenFallback( address _origin, uint _value, bytes _data) public returns (bool ok); } 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract iERC20Token { uint256 public totalSupply = 0; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library SafeERC20 { function safeTransfer(StandardToken token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(StandardToken token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(StandardToken token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract StandardToken is iERC20Token { using SafeMath for uint256; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) public returns (bool success) { 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; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { 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; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint 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); 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract FreezableToken is iERC223Token, StandardToken, Ownable { event ContractTransfer(address indexed _from, address indexed _to, uint _value, bytes _data); bool public freezed; modifier canTransfer(address _transferer) { require(owner == _transferer || !freezed); _; } function FreezableToken() public { freezed = true; } function transfer(address _to, uint _value, bytes _data) canTransfer(msg.sender) public canTransfer(msg.sender) returns (bool success) { //filtering if the target is a contract with bytecode inside it require(super.transfer(_to, _value)); // do a normal token transfer if (isContract(_to)) { require(contractFallback(msg.sender, _to, _value, _data)); } return true; } function transferFrom(address _from, address _to, uint _value, bytes _data) public canTransfer(msg.sender) returns (bool success) { require(super.transferFrom(_from, _to, _value)); // do a normal token transfer if (isContract(_to)) { require(contractFallback(_from, _to, _value, _data)); } return true; } function transfer(address _to, uint _value) canTransfer(msg.sender) public canTransfer(msg.sender) returns (bool success) { return transfer(_to, _value, new bytes(0)); } function transferFrom(address _from, address _to, uint _value) public canTransfer(msg.sender) returns (bool success) { return transferFrom(_from, _to, _value, new bytes(0)); } //function that is called when transaction target is a contract function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool) { ContractTransfer(_origin, _to, _value, _data); ERC223Receiver reciever = ERC223Receiver(_to); require(reciever.tokenFallback(_origin, _value, _data)); return true; } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return length > 0; } function unfreeze() public onlyOwner returns (bool){ freezed = false; return true; } } contract SimpleMultisigWallet is ERC223Receiver { // Max size of owners that can be added to wallet uint constant private MAX_OWNER_COUNT = 5; /** * event for transaction confirmation logging * @param sender who confirmed transaction * @param transactionId transaction identifier * @param createdOn time of log */ event Confirmation(address sender, uint transactionId, uint256 createdOn); /** * event for transaction revocation logging * @param sender who confirmed transaction * @param transactionId transaction identifier * @param createdOn time of log */ event Revocation(address sender, uint transactionId, uint256 createdOn); /** * event for transaction submission logging * @param transactionId transaction identifier * @param token token contract address if transaction submits tokens * @param transactionType type of transaction showing if tokens or ether is submited * @param createdOn time of log */ event Submission(uint indexed transactionId, address indexed token, address indexed newOwner, TransactionType transactionType, uint256 createdOn); /** * event for transaction execution logging * @param transactionId transaction identifier * @param createdOn time of log */ event Execution(uint indexed transactionId, uint256 createdOn); /** * event for deposit logging * @param sender account who send ether * @param value amount of wei which was sent * @param createdOn time of log */ event Deposit(address indexed sender, uint value, uint256 createdOn); /** * event for owner addition logging * @param owner new added wallet owner * @param createdOn time of log */ event OwnerAddition(address indexed owner, uint256 createdOn); /** * event for owner removal logging * @param owner wallet owner who was removed from wallet * @param createdOn time of log */ event OwnerRemoval(address indexed owner, uint256 createdOn); /** * event for needed confirmation requirement change logging * @param required number of confirmation needed for action to be proceeded * @param createdOn time of log *//* event RequirementChange(uint required, uint256 createdOn);*/ // dictionary which shows transaction info by transaction identifer mapping (uint => Transaction) public transactions; // dictionary which shows which owners confirmed transactions mapping (uint => mapping (address => bool)) public confirmations; // dictionary which shows if ether account is owner mapping (address => bool) internal isOwner; // owners of wallet address[] internal owners; // number of confirmation which is needed to action be proceeded uint internal required; //total transaction count uint public transactionCount; // dictionary which shows owners who confirmed new owner addition mapping(address => address[]) private ownersConfirmedOwnerAdd; // dictionary which shows owners who confirmed existing owner remove mapping(address => address[]) private ownersConfirmedOwnerRemove; // Type which identifies if transaction will operate with ethers or tokens enum TransactionType{Standard, Token, Unfreeze, PassOwnership} // Structure of detailed transaction information struct Transaction { address token; address destination; uint value; TransactionType transactionType; bool executed; } modifier notConfirmedOwnerAdd(address _owner) { for(uint i = 0; i < ownersConfirmedOwnerAdd[_owner].length; i++){ require(ownersConfirmedOwnerAdd[_owner][i] != msg.sender); } _; } modifier notConfirmedOwnerRemove(address _owner) { for(uint i = 0; i < ownersConfirmedOwnerRemove[_owner].length; i++){ require(ownersConfirmedOwnerRemove[_owner][i] != msg.sender); } _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require (transactions[transactionId].destination != 0 || transactions[transactionId].token != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(transactionId >= 0 && transactionId < transactionCount); require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(transactionId >= 0 && transactionId < transactionCount); require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require (_address != 0x0); _; } modifier validRequirement(uint _ownersCount, uint _required) { require(_ownersCount <= MAX_OWNER_COUNT); require(_required <= _ownersCount); require(_required > 1); require(_ownersCount > 1); _; } modifier validTransaction(address destination, uint value) { require(destination != 0x0); require(value > 0); _; } modifier validTokenTransaction(address token, address destination, uint value) { require(token != 0x0); require(destination != 0x0); require(value > 0); _; } modifier validFreezableToken(address token) { require(token != 0x0); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0){ Deposit(msg.sender, msg.value, now); } } /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required number of needed confirmation to proceed any action function SimpleMultisigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; // owners.push(msg.sender); // isOwner[msg.sender] = true; require(_required <= owners.length); required = _required; } function getOwners() public view returns(address[]) { return owners; } function removeOwnersConfirmations(address _owner) private { uint[] memory transactionIds = ownersConfirmedTransactions(_owner); for (uint i = 0; i < transactionIds.length; i++) { confirmations[transactionIds[i]][_owner] = false; } } /*/// @dev Allows to change the number of required confirmations. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public ownerExists(msg.sender) validRequirement(owners.length, _required) { required = _required; RequirementChange(_required, now); }*/ /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function submitTransaction(address destination, uint value) public ownerExists(msg.sender) validTransaction(destination, value) returns (uint) { require(address(this).balance >= value); uint transactionId = addTransaction(0x0, destination, value, TransactionType.Standard); confirmTransaction(transactionId); return transactionId; } /// @dev Allows an owner to submit and confirm a token transaction. /// @param token address of token SC which supply will b transferred. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function submitTokenTransaction(address token, address destination, uint value) public ownerExists(msg.sender) validTokenTransaction(token, destination, value) returns (uint) { require(StandardToken(token).balanceOf(address(this)) >= value); uint transactionId = addTransaction(token, destination, value, TransactionType.Token); confirmTransaction(transactionId); return transactionId; } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) returns (bool) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId, now); executeTransaction(transactionId); return true; } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId, now); } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i=0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]){ count += 1; } if (count == required){ return true; } } return false; } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) returns(bool) { if (transactions[transactionId].transactionType == TransactionType.Standard && isConfirmed(transactionId) && this.balance >= transactions[transactionId].value) { transactions[transactionId].executed = true; transactions[transactionId].destination.transfer(transactions[transactionId].value); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.Token && isConfirmed(transactionId) && StandardToken(transactions[transactionId].token).balanceOf(address(this)) >= transactions[transactionId].value) { transactions[transactionId].executed = true; StandardToken(transactions[transactionId].token).transfer(transactions[transactionId].destination, transactions[transactionId].value); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.Unfreeze && isConfirmed(transactionId)) { transactions[transactionId].executed = true; FreezableToken(transactions[transactionId].token).unfreeze(); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.PassOwnership && isConfirmed(transactionId)) { transactions[transactionId].executed = true; Ownable(transactions[transactionId].token).transferOwnership(transactions[transactionId].destination); Execution(transactionId, now); return true; } return false; } /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether/token value. /// @param transactionType Transaction type (Standard/token). /// @return Returns transaction ID. function addTransaction(address token, address destination, uint value, TransactionType transactionType) internal notNull(destination) returns (uint) { uint transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, token: token, value: value, transactionType: transactionType, executed: false }); transactionCount += 1; Submission(transactionId, token, 0x0, transactionType, now); return transactionId; } /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint founded) { for (uint i=0; i < transactionCount; i++) { if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { founded += 1; } } } /// @dev Check balance of holding specific tokens /// @param token address of token /// @return balance of tokens function tokenBalance(StandardToken token) public view returns(uint) { return token.balanceOf(address(this)); } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count; uint i; for (i=0; i < transactionCount; i++){ if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { transactionIdsTemp[count] = i; count +=1; } } if(to > count) { to = count; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } function ownersConfirmedTransactions(address _owner) public view ownerExists(msg.sender) returns(uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i < transactionCount; i++){ if (confirmations[i][_owner]) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](count); for(i = 0; i< count; i++){ _transactionIds[i] = transactionIdsTemp[i]; } } /// @dev Implementation of ERC223 receiver fallback function in order to protect /// @dev sending tokens (standard ERC223) to smart tokens who doesn&#39;t except them function tokenFallback(address /*_origin*/, uint /*_value*/, bytes /*_data*/) public returns (bool ok) { return true; } } contract SimpleTokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for StandardToken; event Released(uint256 amount, uint releaseDate); // beneficiary of tokens after they are released address public beneficiary; uint256 public vestedDate; mapping(address => uint256) public released; modifier vested() { require(now >= vestedDate); _; } /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _vestedDate the period in which the tokens will vest */ function SimpleTokenVesting(address _beneficiary, uint256 _vestedDate) public { require(_beneficiary != address(0)); require(_vestedDate >= now); beneficiary = _beneficiary; vestedDate = _vestedDate; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(StandardToken token) vested public { uint256 unreleased = token.balanceOf(this); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased, now); } /// @dev Implementation of ERC223 receiver fallback function in order to protect /// @dev sending tokens (standard ERC223) to smart tokens who doesn&#39;t except them function tokenFallback(address /*_origin*/, uint /*_value*/, bytes /*_data*/) pure public returns (bool ok) { return true; } } contract VestedMultisigWallet is SimpleMultisigWallet { //date till when multi-signature wallet will be vested uint public vestedDate; /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required number of needed confirmation to proceed any action /// @param _vestedDate date till when multisignature will be vested function VestedMultisigWallet(address[] _owners, uint _required, uint _vestedDate) SimpleMultisigWallet(_owners, _required) public { vestedDate = _vestedDate; } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) returns(bool) { if (transactions[transactionId].transactionType == TransactionType.Standard && isConfirmed(transactionId) && this.balance >= transactions[transactionId].value) { transactions[transactionId].executed = true; transactions[transactionId].destination.transfer(transactions[transactionId].value); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.Token && isConfirmed(transactionId) && StandardToken(transactions[transactionId].token).balanceOf(address(this)) >= transactions[transactionId].value) { require(now >= vestedDate); transactions[transactionId].executed = true; StandardToken(transactions[transactionId].token).transfer(transactions[transactionId].destination, transactions[transactionId].value); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.Unfreeze && isConfirmed(transactionId)) { transactions[transactionId].executed = true; FreezableToken(transactions[transactionId].token).unfreeze(); Execution(transactionId, now); return true; } else if(transactions[transactionId].transactionType == TransactionType.PassOwnership && isConfirmed(transactionId)) { transactions[transactionId].executed = true; Ownable(transactions[transactionId].token).transferOwnership(transactions[transactionId].destination); Execution(transactionId, now); return true; } return false; } }
do a normal token transfer
require(super.transfer(_to, _value));
2,191,648
[ 1, 2896, 279, 2212, 1147, 7412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 9565, 18, 13866, 24899, 869, 16, 389, 1132, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x14E252759e82317bb46e38cD6Fb62F77Ab93f070/sources/contracts/Contract.sol
@title ERC1155 token @author Liam Arbuckle/
contract Portal is ERC1155Supply, ERC1155Burnable, Ownable { string name_; string symbol_; uint256 constant MAX_SUPPLY = 1000; uint256 public whiteListSalePrice = 12 * 10 ** 16; uint256 public publicSalePrice = 12 * 10 ** 16; uint256 public publicMaxMintableCount = 10; uint256 public NOT_MINTABLE = 0; uint256 public PRESALE_STAGE_ONE = 1; uint256 public PRESALE_STAGE_TWO = 2; uint256 public PUBLIC_SALE = 3; struct WhiteList { uint256 maxAmount; bool minted; } mapping(uint256 => uint256) public mintedCounterTokenId; mapping(uint256 => mapping(address => bool)) public hasNft; mapping(uint256 => mapping(address => bool)) public whitelistedOne; mapping(uint256 => mapping(address => bool)) public whitelistedTwo; mapping(uint256 => mapping(uint256 => mapping(address => WhiteList))) public whitelistStatus; mapping(uint256 => uint256) public saleStage; address private _withdrawal = 0x15A4C3b42f3386Cd1A642908525469684Cac7C6d; modifier checkTokenId (uint256 tokenId_) { require(tokenId_ >= 0 && tokenId_ <= 4, "Invalid token id"); _; } string memory _name, string memory _symbol, string memory _uri constructor( ) ERC1155(_uri) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } function getMaxMintableCount(uint256 tokenId_, address user_) public view returns (uint256) { uint256 currentStage = saleStage[tokenId_]; if (currentStage == NOT_MINTABLE) return 0; else if (currentStage == PUBLIC_SALE) { if (hasNft[tokenId_][user_] == true) return 0; return publicMaxMintableCount; } else { if (whitelistStatus[tokenId_][currentStage][user_].minted == true) return 0; return whitelistStatus[tokenId_][currentStage][user_].maxAmount; } } function getMaxMintableCount(uint256 tokenId_, address user_) public view returns (uint256) { uint256 currentStage = saleStage[tokenId_]; if (currentStage == NOT_MINTABLE) return 0; else if (currentStage == PUBLIC_SALE) { if (hasNft[tokenId_][user_] == true) return 0; return publicMaxMintableCount; } else { if (whitelistStatus[tokenId_][currentStage][user_].minted == true) return 0; return whitelistStatus[tokenId_][currentStage][user_].maxAmount; } } function getMaxMintableCount(uint256 tokenId_, address user_) public view returns (uint256) { uint256 currentStage = saleStage[tokenId_]; if (currentStage == NOT_MINTABLE) return 0; else if (currentStage == PUBLIC_SALE) { if (hasNft[tokenId_][user_] == true) return 0; return publicMaxMintableCount; } else { if (whitelistStatus[tokenId_][currentStage][user_].minted == true) return 0; return whitelistStatus[tokenId_][currentStage][user_].maxAmount; } } function setPublicMaxMintableCount(uint256 count_) public onlyOwner { publicMaxMintableCount = count_; } function addUserToWhiteList(uint256 tokenId_, uint256 stage_, address user_, uint256 amount_) public onlyOwner checkTokenId(tokenId_) { require(stage_ == PRESALE_STAGE_ONE || stage_ == PRESALE_STAGE_TWO, "Invalid stage"); if (stage_ == PRESALE_STAGE_ONE) { require(whitelistedTwo[tokenId_][user_] != true, "You already whitelisted in whitelist2"); whitelistedOne[tokenId_][user_] = true; } if (stage_ == PRESALE_STAGE_TWO) { require(whitelistedOne[tokenId_][user_] != true, "You already whitelisted in whitelist1"); whitelistedTwo[tokenId_][user_] = true; } WhiteList memory whitelist = WhiteList(amount_, false); whitelistStatus[tokenId_][stage_][user_] = whitelist; } function addUserToWhiteList(uint256 tokenId_, uint256 stage_, address user_, uint256 amount_) public onlyOwner checkTokenId(tokenId_) { require(stage_ == PRESALE_STAGE_ONE || stage_ == PRESALE_STAGE_TWO, "Invalid stage"); if (stage_ == PRESALE_STAGE_ONE) { require(whitelistedTwo[tokenId_][user_] != true, "You already whitelisted in whitelist2"); whitelistedOne[tokenId_][user_] = true; } if (stage_ == PRESALE_STAGE_TWO) { require(whitelistedOne[tokenId_][user_] != true, "You already whitelisted in whitelist1"); whitelistedTwo[tokenId_][user_] = true; } WhiteList memory whitelist = WhiteList(amount_, false); whitelistStatus[tokenId_][stage_][user_] = whitelist; } function addUserToWhiteList(uint256 tokenId_, uint256 stage_, address user_, uint256 amount_) public onlyOwner checkTokenId(tokenId_) { require(stage_ == PRESALE_STAGE_ONE || stage_ == PRESALE_STAGE_TWO, "Invalid stage"); if (stage_ == PRESALE_STAGE_ONE) { require(whitelistedTwo[tokenId_][user_] != true, "You already whitelisted in whitelist2"); whitelistedOne[tokenId_][user_] = true; } if (stage_ == PRESALE_STAGE_TWO) { require(whitelistedOne[tokenId_][user_] != true, "You already whitelisted in whitelist1"); whitelistedTwo[tokenId_][user_] = true; } WhiteList memory whitelist = WhiteList(amount_, false); whitelistStatus[tokenId_][stage_][user_] = whitelist; } function moveToNextStage(uint256 tokenId_) public onlyOwner checkTokenId(tokenId_) { require(saleStage[tokenId_] < PUBLIC_SALE, "Now it's public sale. there is no more steps."); saleStage[tokenId_] += 1; } function moveToPreviousStage(uint256 tokenId_) public onlyOwner checkTokenId(tokenId_) { require(saleStage[tokenId_] > NOT_MINTABLE, "there is no more steps to move previous."); saleStage[tokenId_] -= 1; } function mint(uint256 tokenId_, uint256 amount_) public payable { require(totalSupply(tokenId_) + amount_ < MAX_SUPPLY, "Maximum amount exceed"); require(amount_ > 0, "amount invalid"); uint256 currentStage = saleStage[tokenId_]; require(currentStage != NOT_MINTABLE, "It is not on sale stage."); if (currentStage == PUBLIC_SALE) { if (tokenId_ == 3) { require(msg.value == publicSalePrice, "Invalid price"); } require(amount_ <= publicMaxMintableCount, "amount should be equal or less than max amount"); require(hasNft[tokenId_][msg.sender] != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); hasNft[tokenId_][msg.sender] = true; if (tokenId_ == 3) { require(msg.value == whiteListSalePrice, "Invalid price"); } require(whitelistedOne[tokenId_][msg.sender] == true || whitelistedTwo[tokenId_][msg.sender] == true, "You are not whitelisted"); require(amount_ <= whitelistStatus[tokenId_][currentStage][msg.sender].maxAmount, "amount should be equal or less than max amount"); require(whitelistStatus[tokenId_][currentStage][msg.sender].minted != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); whitelistStatus[tokenId_][currentStage][msg.sender].minted = true; } } function mint(uint256 tokenId_, uint256 amount_) public payable { require(totalSupply(tokenId_) + amount_ < MAX_SUPPLY, "Maximum amount exceed"); require(amount_ > 0, "amount invalid"); uint256 currentStage = saleStage[tokenId_]; require(currentStage != NOT_MINTABLE, "It is not on sale stage."); if (currentStage == PUBLIC_SALE) { if (tokenId_ == 3) { require(msg.value == publicSalePrice, "Invalid price"); } require(amount_ <= publicMaxMintableCount, "amount should be equal or less than max amount"); require(hasNft[tokenId_][msg.sender] != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); hasNft[tokenId_][msg.sender] = true; if (tokenId_ == 3) { require(msg.value == whiteListSalePrice, "Invalid price"); } require(whitelistedOne[tokenId_][msg.sender] == true || whitelistedTwo[tokenId_][msg.sender] == true, "You are not whitelisted"); require(amount_ <= whitelistStatus[tokenId_][currentStage][msg.sender].maxAmount, "amount should be equal or less than max amount"); require(whitelistStatus[tokenId_][currentStage][msg.sender].minted != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); whitelistStatus[tokenId_][currentStage][msg.sender].minted = true; } } function mint(uint256 tokenId_, uint256 amount_) public payable { require(totalSupply(tokenId_) + amount_ < MAX_SUPPLY, "Maximum amount exceed"); require(amount_ > 0, "amount invalid"); uint256 currentStage = saleStage[tokenId_]; require(currentStage != NOT_MINTABLE, "It is not on sale stage."); if (currentStage == PUBLIC_SALE) { if (tokenId_ == 3) { require(msg.value == publicSalePrice, "Invalid price"); } require(amount_ <= publicMaxMintableCount, "amount should be equal or less than max amount"); require(hasNft[tokenId_][msg.sender] != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); hasNft[tokenId_][msg.sender] = true; if (tokenId_ == 3) { require(msg.value == whiteListSalePrice, "Invalid price"); } require(whitelistedOne[tokenId_][msg.sender] == true || whitelistedTwo[tokenId_][msg.sender] == true, "You are not whitelisted"); require(amount_ <= whitelistStatus[tokenId_][currentStage][msg.sender].maxAmount, "amount should be equal or less than max amount"); require(whitelistStatus[tokenId_][currentStage][msg.sender].minted != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); whitelistStatus[tokenId_][currentStage][msg.sender].minted = true; } } } else { function mint(uint256 tokenId_, uint256 amount_) public payable { require(totalSupply(tokenId_) + amount_ < MAX_SUPPLY, "Maximum amount exceed"); require(amount_ > 0, "amount invalid"); uint256 currentStage = saleStage[tokenId_]; require(currentStage != NOT_MINTABLE, "It is not on sale stage."); if (currentStage == PUBLIC_SALE) { if (tokenId_ == 3) { require(msg.value == publicSalePrice, "Invalid price"); } require(amount_ <= publicMaxMintableCount, "amount should be equal or less than max amount"); require(hasNft[tokenId_][msg.sender] != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); hasNft[tokenId_][msg.sender] = true; if (tokenId_ == 3) { require(msg.value == whiteListSalePrice, "Invalid price"); } require(whitelistedOne[tokenId_][msg.sender] == true || whitelistedTwo[tokenId_][msg.sender] == true, "You are not whitelisted"); require(amount_ <= whitelistStatus[tokenId_][currentStage][msg.sender].maxAmount, "amount should be equal or less than max amount"); require(whitelistStatus[tokenId_][currentStage][msg.sender].minted != true, "You already minted"); _mint(msg.sender, tokenId_, amount_, ""); whitelistStatus[tokenId_][currentStage][msg.sender].minted = true; } } function burnEachOfAmount(uint256 amount, address account) public { require(msg.sender == burningOwner, "You are not able to call this function"); for(uint256 i=0; i<=4; i++) { _burn(account, i, amount); } } function burnEachOfAmount(uint256 amount, address account) public { require(msg.sender == burningOwner, "You are not able to call this function"); for(uint256 i=0; i<=4; i++) { _burn(account, i, amount); } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function withdrawFunds() public onlyOwner returns(bool) { require(address(this).balance > 0, "Unable to withdraw!"); uint balance = address(this).balance; bool sent = false; if (!sent) return false; return true; } (sent,) = _withdrawal.call{value: balance }(""); }
1,869,804
[ 1, 654, 39, 2499, 2539, 1147, 225, 27897, 301, 1201, 70, 9031, 298, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 25478, 353, 4232, 39, 2499, 2539, 3088, 1283, 16, 4232, 39, 2499, 2539, 38, 321, 429, 16, 14223, 6914, 288, 203, 565, 533, 508, 67, 31, 203, 565, 533, 3273, 67, 31, 203, 203, 565, 2254, 5034, 5381, 4552, 67, 13272, 23893, 273, 4336, 31, 203, 565, 2254, 5034, 1071, 27859, 30746, 5147, 273, 2593, 380, 1728, 2826, 2872, 31, 203, 565, 2254, 5034, 1071, 1071, 30746, 5147, 273, 2593, 380, 1728, 2826, 2872, 31, 203, 565, 2254, 5034, 1071, 1071, 2747, 49, 474, 429, 1380, 273, 1728, 31, 203, 203, 565, 2254, 5034, 1071, 4269, 67, 49, 3217, 2782, 273, 374, 31, 203, 565, 2254, 5034, 1071, 7071, 5233, 900, 67, 882, 2833, 67, 5998, 273, 404, 31, 203, 565, 2254, 5034, 1071, 7071, 5233, 900, 67, 882, 2833, 67, 18869, 51, 273, 576, 31, 203, 565, 2254, 5034, 1071, 17187, 67, 5233, 900, 273, 890, 31, 203, 203, 203, 565, 1958, 30233, 682, 288, 203, 3639, 2254, 5034, 943, 6275, 31, 203, 3639, 1426, 312, 474, 329, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 312, 474, 329, 4789, 1345, 548, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 711, 50, 1222, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 26944, 3335, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 26944, 11710, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2 ]
./full_match/3/0x6579377e88f6D65C5a88a608a8AC20F6De51ce16/sources/contracts/BBC.sol
Faciliating the needed functionality for the presale
contract BBC is ERC721Enumerable, Ownable { uint256 public constant MAX_KOALAS = 10000; uint256 public constant RESERVES = 100; uint256 private _conversionRate = 7; mapping(address => bool) addressToPreSaleEntry; mapping(address => uint256) addressToPreSaleKoalasMinted; string private _baseTokenURI; constructor(string memory baseURI, address[] memory preSaleWalletAddresses) ERC721("BBC", "BBC") { setBaseURI(baseURI); for (uint256 i; i < preSaleWalletAddresses.length; i++) { addressToPreSaleEntry[preSaleWalletAddresses[i]] = true; } } { setBaseURI(baseURI); for (uint256 i; i < preSaleWalletAddresses.length; i++) { addressToPreSaleEntry[preSaleWalletAddresses[i]] = true; } } modifier preSaleIsOpen() { require( block.timestamp >= _saleTime - 171900, "The presale has not yet started." ); require( block.timestamp < _saleTime, "The public sale has already started." ); _; } modifier saleIsOpen() { require(block.timestamp >= _saleTime, "Sale is not yet open."); _; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setSaleTime(uint256 _time) public onlyOwner { _saleTime = _time; } function getSaleTime() public view returns (uint256) { return _saleTime; } function setConversionRate(uint256 _val) public onlyOwner { _conversionRate = _val; } function getConversionRate() public view returns (uint256) { return _conversionRate; } function setPrice(uint256 _newWEIPrice) public onlyOwner { _price = _newWEIPrice; } function getPrice() public view returns (uint256) { return _price; } function addWalletToPreSale(address _address) public onlyOwner { addressToPreSaleEntry[_address] = true; } function isWalletInPreSale(address _address) public view returns (bool) { return addressToPreSaleEntry[_address]; } function preSaleKoalasMinted(address _address) public view returns (uint256) { return addressToPreSaleKoalasMinted[_address]; } function preSaleMint(uint256 _count) public payable preSaleIsOpen { uint256 totalSupply = totalSupply(); require( _count <= _conversionRate, "Mint transaction exceeds your available supply." ); require( addressToPreSaleEntry[msg.sender] == true, "This address is not whitelisted for the presale." ); require( addressToPreSaleKoalasMinted[msg.sender] + _count <= _conversionRate, "Exceeds supply of presale Koalas you can mint." ); require(_price * _count <= msg.value, "Transaction value too low."); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } function preSaleMint(uint256 _count) public payable preSaleIsOpen { uint256 totalSupply = totalSupply(); require( _count <= _conversionRate, "Mint transaction exceeds your available supply." ); require( addressToPreSaleEntry[msg.sender] == true, "This address is not whitelisted for the presale." ); require( addressToPreSaleKoalasMinted[msg.sender] + _count <= _conversionRate, "Exceeds supply of presale Koalas you can mint." ); require(_price * _count <= msg.value, "Transaction value too low."); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } addressToPreSaleKoalasMinted[msg.sender] += _count; function mint(uint256 _count) public payable saleIsOpen { uint256 totalSupply = totalSupply(); require( _count < _maxPerTx, "Woah, Nelly. That's way too many Koalas to mint!" ); require(totalSupply < MAX_KOALAS, "All Koalas are already minted."); require( totalSupply + _count <= MAX_KOALAS, "This amount of Koalas will exceed max supply." ); require(_price * _count <= msg.value, "Transaction value too low."); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } function mint(uint256 _count) public payable saleIsOpen { uint256 totalSupply = totalSupply(); require( _count < _maxPerTx, "Woah, Nelly. That's way too many Koalas to mint!" ); require(totalSupply < MAX_KOALAS, "All Koalas are already minted."); require( totalSupply + _count <= MAX_KOALAS, "This amount of Koalas will exceed max supply." ); require(_price * _count <= msg.value, "Transaction value too low."); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } function reserveKoalas(uint256 _count) public onlyOwner { uint256 totalSupply = totalSupply(); require( block.timestamp < _saleTime - 171900, "Sale has already started." ); require(totalSupply + _count <= RESERVES, "Beyond max limit"); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } function reserveKoalas(uint256 _count) public onlyOwner { uint256 totalSupply = totalSupply(); require( block.timestamp < _saleTime - 171900, "Sale has already started." ); require(totalSupply + _count <= RESERVES, "Beyond max limit"); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, totalSupply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
14,213,838
[ 1, 6645, 15700, 1776, 326, 3577, 14176, 364, 326, 4075, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 16283, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 47, 51, 1013, 3033, 273, 12619, 31, 203, 565, 2254, 5034, 1071, 5381, 2438, 2123, 3412, 55, 273, 2130, 31, 203, 203, 565, 2254, 5034, 3238, 389, 20990, 4727, 273, 2371, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1758, 774, 1386, 30746, 1622, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1758, 774, 1386, 30746, 47, 83, 287, 345, 49, 474, 329, 31, 203, 203, 565, 533, 3238, 389, 1969, 1345, 3098, 31, 203, 203, 565, 3885, 12, 1080, 3778, 1026, 3098, 16, 1758, 8526, 3778, 675, 30746, 16936, 7148, 13, 203, 3639, 4232, 39, 27, 5340, 2932, 9676, 39, 3113, 315, 9676, 39, 7923, 203, 203, 203, 203, 203, 203, 565, 288, 203, 3639, 26435, 3098, 12, 1969, 3098, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 675, 30746, 16936, 7148, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 774, 1386, 30746, 1622, 63, 1484, 30746, 16936, 7148, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 26435, 3098, 12, 1969, 3098, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 675, 30746, 16936, 7148, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 774, 1386, 30746, 1622, 63, 1484, 30746, 16936, 7148, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 9606, 675, 30746, 2 ]
./partial_match/1/0x9dA0a4565Dd11c42148729eAC420C50B92EeaBFD/sources/turkeysGameFarmers.sol
Events Hard variables Public variables Mappings Non-stake Staking
contract turkeysGameFarmers is ERC721Enumerable, Ownable, Pausable { using SafeMath for uint256; using Strings for uint256; event TurkeyStampede(uint256 lostAmount, uint256 transferredAmount); event HungryTurkeys(uint256 lostAmount, uint256 transferredAmount); event TurkeyTime(uint256 lostAmount, uint256 transferredAmount); event TurkeyStrike(uint256 lostAmount, uint256 transferredAmount); event RogueTurkey(uint256 lostAmount, uint256 transferredAmount); IERC20 public paymentToken = IERC20(0x85Cd22083260e1D6C869ca7D89b0c8B5428e3c92); VEGInterface public vegContract = VEGInterface(0x85Cd22083260e1D6C869ca7D89b0c8B5428e3c92); address public LOST_REWARDS_ADDRESS = 0x4479bd2906437668c14B130797b9b94982D1a2bc; address DEAD = 0x000000000000000000000000000000000000dEaD; OldContractInterface public oldContract = OldContractInterface(0x8f1F19Fa03475028c594533e2697F29AFA16d06F); uint256 public currentPrice = 500 * 10**9; uint256 public totalMinted = 0; uint256 public REWARD_RATE_PER_SECOND = 100 * 10**9; uint256 public constant MAX_SUPPLY = 4444; uint256 public defaultAddressBonus = 30; uint256 public defaultYieldBonus = 0; uint256 public maxDamage = 30; uint256 public nextRevivalTokenID = 4445; uint256 public revivalFee = 400 * 10**9; uint256 public healthResetFee = 30 * 10**9; uint256 public nextItemId = 1; mapping(address => StakeInfo) public stakers; mapping(uint256 => StakeInfo) public tokenStakers; mapping(address => uint256) public addressBonus; mapping(address => bool) private hasExplicitBonus; mapping(address => uint256) public rewardsUsedForMinting; mapping(uint256 => uint256) public farmerHealth; mapping(address => bool) private _gameControllers; mapping(address => uint256) public yieldBonus; mapping(address => bool) private hasYieldBonus; mapping(uint256 => bool) public deadFarmers; mapping(address => bool) public hasMigrated; mapping(address => uint256[]) public itemsBoughtByUser; mapping(uint256 => Item) public items; mapping(uint256 => uint256[]) public tokenIdToItems; mapping(address => mapping(uint256 => uint256)) public userItemCount; struct StakeInfo { uint256 timestamp; uint256 reward; uint256 lastResetTimestamp; bool revived; } struct Item { string name; uint256 price; uint256 addressBonusIncrease; uint256 addressBonusDecrease; uint256 yieldBonus; bool hasYieldBonus; bool hasExplicitBonus; uint256 maxQuantityPerUser; bool exists; } constructor() ERC721("The Farmers | Turkeys.io", "FARMERS") {} modifier onlyGameControllers() { require(isGameController(msg.sender), "Restricted to role members only"); _; } function isGameController(address account) public view returns (bool) { return _gameControllers[account]; } function addGameController(address account) external onlyOwner { require(!isGameController(account), "Address is already a member of the role"); _gameControllers[account] = true; } function removeGameController(address account) external onlyOwner { require(isGameController(account), "Address is not a member of the role"); _gameControllers[account] = false; } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { string memory base = _baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ''; } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function mintMultiple(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalPrice, "Token allowance not provided"); paymentToken.transferFrom(msg.sender, address(DEAD), totalPrice); for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } uint256 numTokens = balanceOf(to); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(to, i); tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function adminMintMultiple(address[] memory recipients, uint256[] memory quantities) external onlyGameControllers { require(recipients.length == quantities.length, "Mismatched arrays"); for (uint256 i = 0; i < recipients.length; i++) { address to = recipients[i]; uint256 quantity = quantities[i]; require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); for (uint256 j = 0; j < quantity; j++) { uint256 newTokenId = totalSupply() + 1; _mint(to, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function migrateNFTs() external { require(!hasMigrated[msg.sender], "Already migrated"); uint256 oldBalance = oldContract.balanceOf(msg.sender); require(oldBalance > 0, "No NFTs to migrate"); for (uint256 i = 0; i < oldBalance; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } hasMigrated[msg.sender] = true; } function migrateNFTs() external { require(!hasMigrated[msg.sender], "Already migrated"); uint256 oldBalance = oldContract.balanceOf(msg.sender); require(oldBalance > 0, "No NFTs to migrate"); for (uint256 i = 0; i < oldBalance; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } hasMigrated[msg.sender] = true; } function migrateNFTs() external { require(!hasMigrated[msg.sender], "Already migrated"); uint256 oldBalance = oldContract.balanceOf(msg.sender); require(oldBalance > 0, "No NFTs to migrate"); for (uint256 i = 0; i < oldBalance; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } hasMigrated[msg.sender] = true; } function migrateNFTs() external { require(!hasMigrated[msg.sender], "Already migrated"); uint256 oldBalance = oldContract.balanceOf(msg.sender); require(oldBalance > 0, "No NFTs to migrate"); for (uint256 i = 0; i < oldBalance; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } hasMigrated[msg.sender] = true; } function migrateNFTs() external { require(!hasMigrated[msg.sender], "Already migrated"); uint256 oldBalance = oldContract.balanceOf(msg.sender); require(oldBalance > 0, "No NFTs to migrate"); for (uint256 i = 0; i < oldBalance; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } hasMigrated[msg.sender] = true; } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function mintMultipleWithRewards(address to, uint256 quantity) external whenNotPaused { require(quantity > 0, "Must mint at least one NFT"); require(totalMinted.add(quantity) <= MAX_SUPPLY, "Exceeds maximum supply"); uint256 totalPrice = currentPrice.mul(quantity); uint256 totalReward = 0; uint256 numTokens = balanceOf(msg.sender); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); totalReward += getPendingReward(tokenId); } require(totalReward >= totalPrice, "Insufficient reward balance"); rewardsUsedForMinting[msg.sender] += totalPrice; for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply() + 1; _mint(msg.sender, newTokenId); totalMinted = totalMinted.add(1); farmerHealth[totalSupply() + 1] = 100; tokenStakers[newTokenId] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } } else { function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } } else { function claim() public whenNotPaused { require(stakers[msg.sender].timestamp > 0, "Not holding or staking any NFTs"); uint256 totalReward = 0; uint256 revivedReward = 0; uint256 numTokens = balanceOf(msg.sender); require(numTokens > 0, "Not holding or staking any NFTs"); for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (farmerHealth[tokenId] == 0) { continue; } uint256 pendingReward = getPendingReward(tokenId); require(pendingReward > 0, "No rewards available for token"); if (tokenStakers[tokenId].revived) { revivedReward += pendingReward; totalReward += pendingReward; } tokenStakers[tokenId].reward = 0; tokenStakers[tokenId].timestamp = block.timestamp; if (farmerHealth[tokenId] > 0) { uint256 damage = (uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (maxDamage - 10)) + 10; if (farmerHealth[tokenId] > damage) { farmerHealth[tokenId] -= damage; deadFarmers[tokenId] = true; } } } uint256 lostReward = 0; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty))) % 51; uint256 lossRatio = getAddressBonus(msg.sender); uint256 lossRatioFinal = (lossRatio == 0) ? 30 : lossRatio; uint256 lossPercentage = randomNumber + lossRatioFinal; lostReward = totalReward.mul(lossPercentage).div(100); uint256 mintFee = rewardsUsedForMinting[msg.sender]; uint256 finalReward = totalReward + revivedReward - lostReward - mintFee; if (randomNumber < 5) { emit TurkeyStampede(lostReward, finalReward); emit HungryTurkeys(lostReward, finalReward); emit TurkeyTime(lostReward, finalReward); emit TurkeyStrike(lostReward, finalReward); emit RogueTurkey(lostReward, finalReward); } rewardsUsedForMinting[msg.sender] = 0; stakers[msg.sender].reward = 0; stakers[msg.sender].timestamp = block.timestamp; vegContract.rewardTokens(msg.sender, LOST_REWARDS_ADDRESS, finalReward, lostReward); } } else if (randomNumber < 20) { } else if (randomNumber < 35) { } else if (randomNumber < 50) { } else { function getPendingReward(uint256 tokenId) public view returns (uint256) { address owner = ownerOf(tokenId); require(owner != address(0), "Token not owned"); if (tokenStakers[tokenId].timestamp == 0) return 0; uint256 stakedDurationInSeconds = block.timestamp.sub(tokenStakers[tokenId].timestamp); uint256 daysHeld = stakedDurationInSeconds.div(86400); if (tokenStakers[tokenId].revived) { return stakedDurationInSeconds.div(86400).mul(20).add(tokenStakers[tokenId].reward); } uint256 rewardRate = REWARD_RATE_PER_SECOND; if (daysHeld > 5) { uint256 reductionDays = daysHeld.sub(4); uint256 reductionPercentage = reductionDays.mul(10); if (reductionPercentage > 90) { reductionPercentage = 90; } rewardRate = REWARD_RATE_PER_SECOND.mul(100 - reductionPercentage).div(100); } uint256[] storage itemIds = tokenIdToItems[tokenId]; for (uint256 i = 0; i < itemIds.length; i++) { uint256 itemId = itemIds[i]; rewardRate += items[itemId].yieldBonus; } return stakedDurationInSeconds.mul(rewardRate).div(86400).add(tokenStakers[tokenId].reward); } function getPendingReward(uint256 tokenId) public view returns (uint256) { address owner = ownerOf(tokenId); require(owner != address(0), "Token not owned"); if (tokenStakers[tokenId].timestamp == 0) return 0; uint256 stakedDurationInSeconds = block.timestamp.sub(tokenStakers[tokenId].timestamp); uint256 daysHeld = stakedDurationInSeconds.div(86400); if (tokenStakers[tokenId].revived) { return stakedDurationInSeconds.div(86400).mul(20).add(tokenStakers[tokenId].reward); } uint256 rewardRate = REWARD_RATE_PER_SECOND; if (daysHeld > 5) { uint256 reductionDays = daysHeld.sub(4); uint256 reductionPercentage = reductionDays.mul(10); if (reductionPercentage > 90) { reductionPercentage = 90; } rewardRate = REWARD_RATE_PER_SECOND.mul(100 - reductionPercentage).div(100); } uint256[] storage itemIds = tokenIdToItems[tokenId]; for (uint256 i = 0; i < itemIds.length; i++) { uint256 itemId = itemIds[i]; rewardRate += items[itemId].yieldBonus; } return stakedDurationInSeconds.mul(rewardRate).div(86400).add(tokenStakers[tokenId].reward); } function getPendingReward(uint256 tokenId) public view returns (uint256) { address owner = ownerOf(tokenId); require(owner != address(0), "Token not owned"); if (tokenStakers[tokenId].timestamp == 0) return 0; uint256 stakedDurationInSeconds = block.timestamp.sub(tokenStakers[tokenId].timestamp); uint256 daysHeld = stakedDurationInSeconds.div(86400); if (tokenStakers[tokenId].revived) { return stakedDurationInSeconds.div(86400).mul(20).add(tokenStakers[tokenId].reward); } uint256 rewardRate = REWARD_RATE_PER_SECOND; if (daysHeld > 5) { uint256 reductionDays = daysHeld.sub(4); uint256 reductionPercentage = reductionDays.mul(10); if (reductionPercentage > 90) { reductionPercentage = 90; } rewardRate = REWARD_RATE_PER_SECOND.mul(100 - reductionPercentage).div(100); } uint256[] storage itemIds = tokenIdToItems[tokenId]; for (uint256 i = 0; i < itemIds.length; i++) { uint256 itemId = itemIds[i]; rewardRate += items[itemId].yieldBonus; } return stakedDurationInSeconds.mul(rewardRate).div(86400).add(tokenStakers[tokenId].reward); } function getPendingReward(uint256 tokenId) public view returns (uint256) { address owner = ownerOf(tokenId); require(owner != address(0), "Token not owned"); if (tokenStakers[tokenId].timestamp == 0) return 0; uint256 stakedDurationInSeconds = block.timestamp.sub(tokenStakers[tokenId].timestamp); uint256 daysHeld = stakedDurationInSeconds.div(86400); if (tokenStakers[tokenId].revived) { return stakedDurationInSeconds.div(86400).mul(20).add(tokenStakers[tokenId].reward); } uint256 rewardRate = REWARD_RATE_PER_SECOND; if (daysHeld > 5) { uint256 reductionDays = daysHeld.sub(4); uint256 reductionPercentage = reductionDays.mul(10); if (reductionPercentage > 90) { reductionPercentage = 90; } rewardRate = REWARD_RATE_PER_SECOND.mul(100 - reductionPercentage).div(100); } uint256[] storage itemIds = tokenIdToItems[tokenId]; for (uint256 i = 0; i < itemIds.length; i++) { uint256 itemId = itemIds[i]; rewardRate += items[itemId].yieldBonus; } return stakedDurationInSeconds.mul(rewardRate).div(86400).add(tokenStakers[tokenId].reward); } function getPendingReward(uint256 tokenId) public view returns (uint256) { address owner = ownerOf(tokenId); require(owner != address(0), "Token not owned"); if (tokenStakers[tokenId].timestamp == 0) return 0; uint256 stakedDurationInSeconds = block.timestamp.sub(tokenStakers[tokenId].timestamp); uint256 daysHeld = stakedDurationInSeconds.div(86400); if (tokenStakers[tokenId].revived) { return stakedDurationInSeconds.div(86400).mul(20).add(tokenStakers[tokenId].reward); } uint256 rewardRate = REWARD_RATE_PER_SECOND; if (daysHeld > 5) { uint256 reductionDays = daysHeld.sub(4); uint256 reductionPercentage = reductionDays.mul(10); if (reductionPercentage > 90) { reductionPercentage = 90; } rewardRate = REWARD_RATE_PER_SECOND.mul(100 - reductionPercentage).div(100); } uint256[] storage itemIds = tokenIdToItems[tokenId]; for (uint256 i = 0; i < itemIds.length; i++) { uint256 itemId = itemIds[i]; rewardRate += items[itemId].yieldBonus; } return stakedDurationInSeconds.mul(rewardRate).div(86400).add(tokenStakers[tokenId].reward); } function getTotalPendingRewards(address user) public view returns (uint256) { uint256 totalRewards = 0; uint256 numTokens = balanceOf(user); uint256 mintFee = rewardsUsedForMinting[msg.sender]; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(user, i); totalRewards += getPendingReward(tokenId); } totalRewards -= mintFee; return totalRewards; } function getTotalPendingRewards(address user) public view returns (uint256) { uint256 totalRewards = 0; uint256 numTokens = balanceOf(user); uint256 mintFee = rewardsUsedForMinting[msg.sender]; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(user, i); totalRewards += getPendingReward(tokenId); } totalRewards -= mintFee; return totalRewards; } function resetRewardsForToken(uint256 tokenId) external onlyGameControllers { tokenStakers[tokenId].lastResetTimestamp = block.timestamp; } function transferFrom(address from, address to, uint256 tokenId) public virtual override(ERC721, IERC721) { super.transferFrom(from, to, tokenId); _updateOnTransfer(from, to); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override(ERC721, IERC721) { super.safeTransferFrom(from, to, tokenId); _updateOnTransfer(from, to); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override(ERC721, IERC721) { super.safeTransferFrom(from, to, tokenId, data); _updateOnTransfer(from, to); } function _updateOnTransfer(address from, address to) internal { if (from != address(0) && balanceOf(from) == 0) { } if (to != address(0) && balanceOf(to) == 1) { if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function _updateOnTransfer(address from, address to) internal { if (from != address(0) && balanceOf(from) == 0) { } if (to != address(0) && balanceOf(to) == 1) { if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function _updateOnTransfer(address from, address to) internal { if (from != address(0) && balanceOf(from) == 0) { } if (to != address(0) && balanceOf(to) == 1) { if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function _updateOnTransfer(address from, address to) internal { if (from != address(0) && balanceOf(from) == 0) { } if (to != address(0) && balanceOf(to) == 1) { if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function _updateOnTransfer(address from, address to) internal { if (from != address(0) && balanceOf(from) == 0) { } if (to != address(0) && balanceOf(to) == 1) { if (stakers[to].timestamp == 0) { stakers[to] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: false }); } } } function firstAidKit(uint256[] memory tokenIds) external { uint256 totalFee = healthResetFee.mul(tokenIds.length); require(paymentToken.balanceOf(msg.sender) >= totalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalFee, "Token allowance not provided"); for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == msg.sender, "Caller is not the owner of this token"); farmerHealth[tokenIds[i]] = 100; } } function firstAidKit(uint256[] memory tokenIds) external { uint256 totalFee = healthResetFee.mul(tokenIds.length); require(paymentToken.balanceOf(msg.sender) >= totalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= totalFee, "Token allowance not provided"); for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == msg.sender, "Caller is not the owner of this token"); farmerHealth[tokenIds[i]] = 100; } } function setFirstAidKitFee(uint256 _healthResetFee) external onlyOwner { healthResetFee = _healthResetFee; } function addItem(string memory _name, uint256 _price, uint256 _addressBonusIncrease, uint256 _addressBonusDecrease, uint256 _yieldBonus, bool _hasRatioBonus, bool _hasYieldBonus, uint256 _maxQuantityPerUser) external { items[nextItemId] = Item({ name: _name, price: _price, addressBonusIncrease: _addressBonusIncrease, addressBonusDecrease: _addressBonusDecrease, yieldBonus: _yieldBonus, hasExplicitBonus: _hasRatioBonus, hasYieldBonus: _hasYieldBonus, maxQuantityPerUser: _maxQuantityPerUser, exists: true }); nextItemId++; } function addItem(string memory _name, uint256 _price, uint256 _addressBonusIncrease, uint256 _addressBonusDecrease, uint256 _yieldBonus, bool _hasRatioBonus, bool _hasYieldBonus, uint256 _maxQuantityPerUser) external { items[nextItemId] = Item({ name: _name, price: _price, addressBonusIncrease: _addressBonusIncrease, addressBonusDecrease: _addressBonusDecrease, yieldBonus: _yieldBonus, hasExplicitBonus: _hasRatioBonus, hasYieldBonus: _hasYieldBonus, maxQuantityPerUser: _maxQuantityPerUser, exists: true }); nextItemId++; } function editItem(uint256 _itemId, string memory _name, uint256 _price, uint256 _addressBonusIncrease, uint256 _addressBonusDecrease, uint256 _yieldBonus, bool _hasRatioBonus, bool _hasYieldBonus, uint256 _maxQuantityPerUser) external { require(_itemId > 0 && _itemId < nextItemId, "Invalid item ID"); require(items[_itemId].exists, "Item does not exist"); items[_itemId] = Item({ name: _name, price: _price, addressBonusIncrease: _addressBonusIncrease, addressBonusDecrease: _addressBonusDecrease, yieldBonus: _yieldBonus, hasExplicitBonus: _hasRatioBonus, hasYieldBonus: _hasYieldBonus, maxQuantityPerUser: _maxQuantityPerUser, exists: true }); } function editItem(uint256 _itemId, string memory _name, uint256 _price, uint256 _addressBonusIncrease, uint256 _addressBonusDecrease, uint256 _yieldBonus, bool _hasRatioBonus, bool _hasYieldBonus, uint256 _maxQuantityPerUser) external { require(_itemId > 0 && _itemId < nextItemId, "Invalid item ID"); require(items[_itemId].exists, "Item does not exist"); items[_itemId] = Item({ name: _name, price: _price, addressBonusIncrease: _addressBonusIncrease, addressBonusDecrease: _addressBonusDecrease, yieldBonus: _yieldBonus, hasExplicitBonus: _hasRatioBonus, hasYieldBonus: _hasYieldBonus, maxQuantityPerUser: _maxQuantityPerUser, exists: true }); } function purchaseItem(uint256 tokenId, uint256 itemId) external { require(items[itemId].exists, "Item does not exist"); uint256 itemPrice = items[itemId].price; require(paymentToken.balanceOf(msg.sender) >= itemPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= itemPrice, "Token allowance not provided"); uint256 maxQuantity = items[itemId].maxQuantityPerUser; require(userItemCount[msg.sender][itemId] < maxQuantity, "You can't buy any more of this."); paymentToken.transferFrom(msg.sender, address(DEAD), itemPrice); tokenIdToItems[tokenId].push(itemId); userItemCount[msg.sender][itemId]++; yieldBonus[msg.sender] += items[itemId].yieldBonus; if (items[itemId].addressBonusIncrease > 0) { if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } } hasYieldBonus[msg.sender] = items[itemId].hasYieldBonus; hasExplicitBonus[msg.sender] = items[itemId].hasExplicitBonus; itemsBoughtByUser[msg.sender].push(itemId); } function purchaseItem(uint256 tokenId, uint256 itemId) external { require(items[itemId].exists, "Item does not exist"); uint256 itemPrice = items[itemId].price; require(paymentToken.balanceOf(msg.sender) >= itemPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= itemPrice, "Token allowance not provided"); uint256 maxQuantity = items[itemId].maxQuantityPerUser; require(userItemCount[msg.sender][itemId] < maxQuantity, "You can't buy any more of this."); paymentToken.transferFrom(msg.sender, address(DEAD), itemPrice); tokenIdToItems[tokenId].push(itemId); userItemCount[msg.sender][itemId]++; yieldBonus[msg.sender] += items[itemId].yieldBonus; if (items[itemId].addressBonusIncrease > 0) { if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } } hasYieldBonus[msg.sender] = items[itemId].hasYieldBonus; hasExplicitBonus[msg.sender] = items[itemId].hasExplicitBonus; itemsBoughtByUser[msg.sender].push(itemId); } function purchaseItem(uint256 tokenId, uint256 itemId) external { require(items[itemId].exists, "Item does not exist"); uint256 itemPrice = items[itemId].price; require(paymentToken.balanceOf(msg.sender) >= itemPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= itemPrice, "Token allowance not provided"); uint256 maxQuantity = items[itemId].maxQuantityPerUser; require(userItemCount[msg.sender][itemId] < maxQuantity, "You can't buy any more of this."); paymentToken.transferFrom(msg.sender, address(DEAD), itemPrice); tokenIdToItems[tokenId].push(itemId); userItemCount[msg.sender][itemId]++; yieldBonus[msg.sender] += items[itemId].yieldBonus; if (items[itemId].addressBonusIncrease > 0) { if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } } hasYieldBonus[msg.sender] = items[itemId].hasYieldBonus; hasExplicitBonus[msg.sender] = items[itemId].hasExplicitBonus; itemsBoughtByUser[msg.sender].push(itemId); } } else if (items[itemId].addressBonusDecrease > 0) { function purchaseItem(uint256 tokenId, uint256 itemId) external { require(items[itemId].exists, "Item does not exist"); uint256 itemPrice = items[itemId].price; require(paymentToken.balanceOf(msg.sender) >= itemPrice, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= itemPrice, "Token allowance not provided"); uint256 maxQuantity = items[itemId].maxQuantityPerUser; require(userItemCount[msg.sender][itemId] < maxQuantity, "You can't buy any more of this."); paymentToken.transferFrom(msg.sender, address(DEAD), itemPrice); tokenIdToItems[tokenId].push(itemId); userItemCount[msg.sender][itemId]++; yieldBonus[msg.sender] += items[itemId].yieldBonus; if (items[itemId].addressBonusIncrease > 0) { if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } if (addressBonus[msg.sender] == 0) { hasExplicitBonus[msg.sender] = true; } } hasYieldBonus[msg.sender] = items[itemId].hasYieldBonus; hasExplicitBonus[msg.sender] = items[itemId].hasExplicitBonus; itemsBoughtByUser[msg.sender].push(itemId); } function getItemsBought(address userAddress) external view returns (uint256[] memory) { return itemsBoughtByUser[userAddress]; } function setYieldBonus(address user, uint256 bonus) external onlyGameControllers { yieldBonus[user] = bonus; hasYieldBonus[user] = true; } function increaseYieldBonus(address user) external onlyGameControllers { uint256 yield = yieldBonus[user]; yieldBonus[user] = yield += 2; hasYieldBonus[user] = true; } function decreaseYieldBonus(address user) external onlyGameControllers { uint256 yield = yieldBonus[user]; yieldBonus[user] = yield -= 2; hasYieldBonus[user] = true; } function getAddressBonus(address user) public view returns (uint256) { if (hasExplicitBonus[user]) { return addressBonus[user]; } return defaultAddressBonus; } function getAddressBonus(address user) public view returns (uint256) { if (hasExplicitBonus[user]) { return addressBonus[user]; } return defaultAddressBonus; } function getYieldBonus(address user) public view returns (uint256) { if (hasYieldBonus[user]) { return yieldBonus[user]; } return defaultYieldBonus; } function getYieldBonus(address user) public view returns (uint256) { if (hasYieldBonus[user]) { return yieldBonus[user]; } return defaultYieldBonus; } function addHealth(uint256 tokenId, uint256 amount) external onlyGameControllers { farmerHealth[tokenId] += amount; } function removeHealth(uint256 tokenId, uint256 amount) external onlyGameControllers { farmerHealth[tokenId] -= amount; if (farmerHealth[tokenId] <= 0) { farmerHealth[tokenId] = 0; deadFarmers[tokenId] = true; } } function removeHealth(uint256 tokenId, uint256 amount) external onlyGameControllers { farmerHealth[tokenId] -= amount; if (farmerHealth[tokenId] <= 0) { farmerHealth[tokenId] = 0; deadFarmers[tokenId] = true; } } function reviveFarmer(uint256 tokenId) external { require(deadFarmers[tokenId], "Farmer is not dead"); require(paymentToken.balanceOf(msg.sender) >= revivalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= revivalFee, "Token allowance not provided"); _burn(tokenId); _mint(msg.sender, nextRevivalTokenID); farmerHealth[nextRevivalTokenID] = 100; nextRevivalTokenID++; deadFarmers[tokenId] = false; if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); } tokenStakers[nextRevivalTokenID] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); paymentToken.transferFrom(msg.sender, address(DEAD), revivalFee); } function reviveFarmer(uint256 tokenId) external { require(deadFarmers[tokenId], "Farmer is not dead"); require(paymentToken.balanceOf(msg.sender) >= revivalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= revivalFee, "Token allowance not provided"); _burn(tokenId); _mint(msg.sender, nextRevivalTokenID); farmerHealth[nextRevivalTokenID] = 100; nextRevivalTokenID++; deadFarmers[tokenId] = false; if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); } tokenStakers[nextRevivalTokenID] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); paymentToken.transferFrom(msg.sender, address(DEAD), revivalFee); } function reviveFarmer(uint256 tokenId) external { require(deadFarmers[tokenId], "Farmer is not dead"); require(paymentToken.balanceOf(msg.sender) >= revivalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= revivalFee, "Token allowance not provided"); _burn(tokenId); _mint(msg.sender, nextRevivalTokenID); farmerHealth[nextRevivalTokenID] = 100; nextRevivalTokenID++; deadFarmers[tokenId] = false; if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); } tokenStakers[nextRevivalTokenID] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); paymentToken.transferFrom(msg.sender, address(DEAD), revivalFee); } function reviveFarmer(uint256 tokenId) external { require(deadFarmers[tokenId], "Farmer is not dead"); require(paymentToken.balanceOf(msg.sender) >= revivalFee, "Insufficient payment token balance"); require(paymentToken.allowance(msg.sender, address(this)) >= revivalFee, "Token allowance not provided"); _burn(tokenId); _mint(msg.sender, nextRevivalTokenID); farmerHealth[nextRevivalTokenID] = 100; nextRevivalTokenID++; deadFarmers[tokenId] = false; if (stakers[msg.sender].timestamp == 0) { stakers[msg.sender] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); } tokenStakers[nextRevivalTokenID] = StakeInfo({ timestamp: block.timestamp, reward: 0, lastResetTimestamp: block.timestamp, revived: true }); paymentToken.transferFrom(msg.sender, address(DEAD), revivalFee); } function getDeadFarmersByWallet(address wallet) public view returns (uint256[] memory) { uint256 numTokens = balanceOf(wallet); uint256[] memory areDeadFarmers = new uint256[](numTokens); uint256 count = 0; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(wallet, i); if (farmerHealth[tokenId] == 0) { areDeadFarmers[count] = tokenId; count++; } } uint256[] memory result = new uint256[](count); for (uint256 i = 0; i < count; i++) { result[i] = areDeadFarmers[i]; } return result; } function getDeadFarmersByWallet(address wallet) public view returns (uint256[] memory) { uint256 numTokens = balanceOf(wallet); uint256[] memory areDeadFarmers = new uint256[](numTokens); uint256 count = 0; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(wallet, i); if (farmerHealth[tokenId] == 0) { areDeadFarmers[count] = tokenId; count++; } } uint256[] memory result = new uint256[](count); for (uint256 i = 0; i < count; i++) { result[i] = areDeadFarmers[i]; } return result; } function getDeadFarmersByWallet(address wallet) public view returns (uint256[] memory) { uint256 numTokens = balanceOf(wallet); uint256[] memory areDeadFarmers = new uint256[](numTokens); uint256 count = 0; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(wallet, i); if (farmerHealth[tokenId] == 0) { areDeadFarmers[count] = tokenId; count++; } } uint256[] memory result = new uint256[](count); for (uint256 i = 0; i < count; i++) { result[i] = areDeadFarmers[i]; } return result; } function getDeadFarmersByWallet(address wallet) public view returns (uint256[] memory) { uint256 numTokens = balanceOf(wallet); uint256[] memory areDeadFarmers = new uint256[](numTokens); uint256 count = 0; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = tokenOfOwnerByIndex(wallet, i); if (farmerHealth[tokenId] == 0) { areDeadFarmers[count] = tokenId; count++; } } uint256[] memory result = new uint256[](count); for (uint256 i = 0; i < count; i++) { result[i] = areDeadFarmers[i]; } return result; } function setUserLossRatio(address user, uint256 bonus) external onlyGameControllers { addressBonus[user] = bonus; hasExplicitBonus[user] = true; } function adjustUserLossRatio(address user) external onlyGameControllers { if (addressBonus[user] == 0) { addressBonus[user] = 28; hasExplicitBonus[user] = true; if (addressBonus[user] > 0) { addressBonus[user] -= 2; } } } function adjustUserLossRatio(address user) external onlyGameControllers { if (addressBonus[user] == 0) { addressBonus[user] = 28; hasExplicitBonus[user] = true; if (addressBonus[user] > 0) { addressBonus[user] -= 2; } } } } else { function adjustUserLossRatio(address user) external onlyGameControllers { if (addressBonus[user] == 0) { addressBonus[user] = 28; hasExplicitBonus[user] = true; if (addressBonus[user] > 0) { addressBonus[user] -= 2; } } } function setDead(address newDead) public onlyOwner { DEAD = newDead; } function setRewardRate(uint256 newRate) public onlyOwner { REWARD_RATE_PER_SECOND = newRate; } function withdrawStuckEther() external onlyOwner { payable(owner()).transfer(address(this).balance); } function withdrawStuckTokens(uint256 amount) external onlyOwner { require(paymentToken.balanceOf(address(this)) >= amount, "Insufficient token balance"); paymentToken.transfer(owner(), amount); } function setRevivalFee(uint256 _revivalFee) external onlyOwner { revivalFee = _revivalFee; } function manualTopUpReward(address _recipient, uint256 _reward) external onlyOwner { require(stakers[_recipient].timestamp != 0, "Recipient is not a staker"); stakers[_recipient].reward = stakers[_recipient].reward.add(_reward); } function pause() external onlyGameControllers { _pause(); } function viewYieldBonus(address _address) public view returns (uint256) { return yieldBonus[_address]; } function unpause() external onlyGameControllers { _unpause(); } function setBaseURI(string calldata newBaseURI) external onlyOwner { _baseTokenURI = newBaseURI; } function getFarmerHealth(uint256 tokenId) public view returns (uint256) { return farmerHealth[tokenId]; } function updatePaymentToken(address _newPaymentToken) external onlyOwner { paymentToken = IERC20(_newPaymentToken); } function updateLostRewardsAddress(address _newLostRewardsAddress) external onlyOwner { LOST_REWARDS_ADDRESS = _newLostRewardsAddress; } function updateVegInterface(address _newVegInterface) external onlyOwner { vegContract = VEGInterface(_newVegInterface); } function updateDefaultYieldBonus(uint256 _newDefaultYieldBonus) external onlyOwner { defaultYieldBonus = _newDefaultYieldBonus; } function updateCurrentPrice(uint256 _newCurrentPrice) external onlyOwner { currentPrice = _newCurrentPrice; } }
4,152,609
[ 1, 3783, 670, 1060, 3152, 7224, 3152, 1635, 4675, 3858, 17, 334, 911, 934, 6159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 268, 295, 2452, 12496, 42, 4610, 414, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 565, 871, 399, 295, 856, 510, 301, 347, 323, 12, 11890, 5034, 13557, 6275, 16, 2254, 5034, 906, 4193, 6275, 1769, 203, 565, 871, 670, 20651, 1176, 56, 295, 2452, 12, 11890, 5034, 13557, 6275, 16, 2254, 5034, 906, 4193, 6275, 1769, 203, 565, 871, 399, 295, 856, 950, 12, 11890, 5034, 13557, 6275, 16, 2254, 5034, 906, 4193, 6275, 1769, 203, 565, 871, 399, 295, 856, 1585, 2547, 12, 11890, 5034, 13557, 6275, 16, 2254, 5034, 906, 4193, 6275, 1769, 203, 565, 871, 534, 717, 344, 56, 295, 856, 12, 11890, 5034, 13557, 6275, 16, 2254, 5034, 906, 4193, 6275, 1769, 203, 203, 203, 565, 467, 654, 39, 3462, 1071, 5184, 1345, 273, 467, 654, 39, 3462, 12, 20, 92, 7140, 19728, 22, 26825, 1578, 4848, 73, 21, 40, 26, 39, 5292, 29, 5353, 27, 40, 6675, 70, 20, 71, 28, 38, 6564, 6030, 73, 23, 71, 9975, 1769, 203, 565, 776, 41, 43, 1358, 1071, 331, 1332, 8924, 273, 776, 41, 43, 1358, 12, 20, 92, 7140, 19728, 22, 26825, 1578, 4848, 73, 21, 40, 26, 39, 5292, 29, 5353, 27, 40, 6675, 70, 20, 71, 28, 38, 6564, 6030, 73, 23, 71, 9975, 1769, 203, 565, 1758, 1071, 1806, 882, 67, 862, 16777, 3948, 67, 15140, 273, 374, 92, 2 ]
pragma solidity ^0.4.21; contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { OwnershipTransferred(owner, newOwner); owner = newOwner; } } } contract EthExploder is Owned { uint256 public jackpotSmall; uint256 public jackpotMedium; uint256 public jackpotLarge; uint256 public houseEarnings; uint256 public houseTotal; uint256 public gameCount; uint16 public smallCount; uint16 public mediumCount; uint16 public largeCount; uint16 public smallSize; uint16 public mediumSize; uint16 public largeSize; uint256 public seed; mapping (uint16 => address) playersSmall; mapping (uint16 => address) playersMedium; mapping (uint16 => address) playersLarge; function enterSmall() payable { require(msg.value > 0); jackpotSmall += msg.value; playersSmall[smallCount] = msg.sender; seed += uint256(msg.sender); if (smallCount < smallSize-1) { smallCount++; } else { seed += gameCount + mediumCount + largeCount; houseEarnings += (jackpotSmall*3)/100; jackpotSmall -= (jackpotSmall*3)/100; uint16 winner = uint16(seed % smallSize); address winning = playersSmall[winner]; //Reset the game: smallCount = 0; uint256 amt = jackpotSmall; jackpotSmall = 0; winning.transfer(amt); gameCount++; emit GameWon(0,winning,amt); } } function enterMedium() payable { require(msg.value > 0); jackpotMedium += msg.value; playersMedium[mediumCount] = msg.sender; seed += uint256(msg.sender); if (mediumCount < mediumSize-1) { mediumCount++; } else { seed += gameCount + smallCount + largeCount; houseEarnings += (jackpotMedium*3)/100; jackpotMedium -= (jackpotMedium*3)/100; uint16 winner = uint16(seed % mediumSize); address winning = playersMedium[winner]; //winning.transfer(jackpotMedium); //Reset the game mediumCount = 0; uint256 amt = jackpotMedium; jackpotMedium = 0; winning.transfer(amt); gameCount++; emit GameWon(1,winning,amt); } } function enterLarge() payable { require(msg.value > 0); jackpotLarge += msg.value; playersLarge[largeCount] = msg.sender; seed += uint256(msg.sender); if (largeCount < largeSize-1) { largeCount++; } else { seed += gameCount + mediumCount + largeCount; houseEarnings += (jackpotLarge*3)/100; jackpotLarge -= (jackpotLarge*3)/100; uint16 winner = uint16(seed % largeSize); address winning = playersLarge[winner]; //Reset the game largeCount = 0; uint256 amt = jackpotLarge; jackpotLarge = 0; winning.transfer(amt); gameCount++; emit GameWon(2,winning,amt); } } function setPools(uint16 sm, uint16 med, uint16 lrg) onlyOwner { smallSize = sm; mediumSize = med; largeSize = lrg; } function claim(address payment) onlyOwner { payment.transfer(houseEarnings); houseTotal += houseEarnings; houseEarnings = 0; } //Prevent accidental ether sending function () payable { revert(); } event GameWon(uint8 gameType, address winner, uint256 winnings); }
Prevent accidental ether sending
function () payable { revert(); } event GameWon(uint8 gameType, address winner, uint256 winnings);
5,995,575
[ 1, 25828, 25961, 287, 225, 2437, 5431, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 8843, 429, 288, 7010, 377, 15226, 5621, 7010, 289, 203, 203, 871, 14121, 59, 265, 12, 11890, 28, 7920, 559, 16, 1758, 5657, 1224, 16, 2254, 5034, 5657, 82, 899, 1769, 7010, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x33AD1d393808DF17dC8e59b8246AC607380b9F01/sources/contracts/king-sniper-amt-addliq.sol
uint256 mpb = getPoolBal(sp.router1, tokenx, sp.weth);
uint256 mpb = 0;
8,364,937
[ 1, 11890, 5034, 312, 5733, 273, 28575, 38, 287, 12, 1752, 18, 10717, 21, 16, 1147, 92, 16, 1694, 18, 91, 546, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 312, 5733, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-06 */ // Sources flattened with hardhat v2.2.0 https://hardhat.org // File openzeppelin-solidity/contracts/utils/introspection/[email protected] // SPDX-License-Identifier: MIT 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-solidity/contracts/token/ERC721/[email protected] 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-solidity/contracts/token/ERC721/[email protected] 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 from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] 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-solidity/contracts/token/ERC721/extensions/[email protected] 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-solidity/contracts/utils/[email protected] 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; // 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); } } } } // File openzeppelin-solidity/contracts/utils/[email protected] 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 openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/token/ERC721/[email protected] 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}. 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 || 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 _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 || ERC721.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 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()) { IERC721Receiver(to).onERC721Received(from, tokenId, _data); } 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` 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 { } } pragma solidity ^ 0.8.0; contract GreenPointLandReserves{ address THIS = address(this); uint $ = 1e18; uint genesis; Totem public totemNFT; ERC20 MVT = ERC20(0x3D46454212c61ECb7b31248047Fa033120B88668); ERC20 MDT = ERC20(0x32A087D5fdF8c84eC32554c56727a7C81124544E); ERC20 COLOR = ERC20(0xe324C8cF74899461Ef7aD2c3EB952DA7819aabc5); Oracle public ORACLE = Oracle(address(0)); address public GLR_nonprofit; address public DEV; address public oracleTeller; uint public GLR_funds; uint public devPot; constructor(){ genesis = block.timestamp; nextFloorRaisingTime = genesis + 86400 * 90; totemNFT = new Totem("Totem","TOTEM"); GLR_nonprofit = msg.sender; DEV = msg.sender; oracleTeller = msg.sender; } function shiftOwnership(address addr) public{ require(msg.sender == GLR_nonprofit); GLR_nonprofit = addr; } function GLR_pullFunds() public{ require(msg.sender == GLR_nonprofit && GLR_funds > 0); uint cash = GLR_funds; GLR_funds = 0; (bool success, ) = GLR_nonprofit.call{value:cash}(""); require(success, "Transfer failed."); } function Dev_pullFunds() public{ require(msg.sender == DEV && devPot > 0); uint cash = devPot; devPot = 0; (bool success, ) = DEV.call{value:cash}(""); require(success, "Transfer failed."); } function shiftDev(address addr) public{ require(msg.sender == DEV); DEV = addr; } function shiftOracleTeller(address addr) public{ require(msg.sender == oracleTeller); oracleTeller = addr; } function setOracle(address addr) public{ require(msg.sender == oracleTeller); ORACLE = Oracle(addr); } function globalData() public view returns(uint _MVT_to_rollout, uint _mvt5xHodlPool, uint _nextFloorRaisingTime, uint _floorPrice, uint _totalACRESupply, uint _totalAcreWeight, uint _totalTotemWeight){ return (MVT_to_rollout, mvt5xHodlPool, nextFloorRaisingTime, floorPrice, _totalSupply, totalShares[ETHpool], totalTotemWeight); } function userData(address account) public view returns(uint acreBalance, uint totemWeight, uint acreDividends, uint totemDividends, bool MDT_approval, bool MVT_approval){ return (balanceOf(account), shares[MVTpool][account], dividendsOf(ETHpool, account) + earnings[ETHpool][account], dividendsOf(MVTpool, account) + earnings[MVTpool][account], MDT.allowance(account,THIS)>$*1000000, MVT.allowance(account,THIS)>$*1000000); } function userData2(address account) public view returns(uint MDT_balance, uint MVT_balance, uint colorDividends){ return ( MDT.balanceOf(account), MVT.balanceOf(account), colorDividendsOf(account) + earnings[COLORpool][account] ); } uint mvt5xHodlPool; event PurchaseAcre(address boughtFor, uint acreBought); function purchaseAcre(address buyFor) public payable{ if( buyFor == address(0) ){ buyFor = msg.sender; } require(msg.value > 0); uint MONEY = msg.value; uint forDev; if(block.timestamp - genesis <= 86400*365){forDev = MONEY * 6/1000;} devPot += forDev; uint val = MONEY - forDev; mint(buyFor, val); uint forBuyingMVT = val * (_totalSupply - totalTotemWeight + builder_totalShares) / _totalSupply; GLR_funds += val - forBuyingMVT; mvt5xHodlPool += forBuyingMVT; emit PurchaseAcre(buyFor, val); rolloutDepositedMVTRewards(); } uint nextFloorRaisingTime; uint floorPrice = $/20000; bool firstBump = true; event Sell_MVT(uint mvtSold, uint cashout); function sell_MVT(uint amount) public{ address payable sender = payable(msg.sender); require( MVT.transferFrom(sender, THIS, amount) ); uint NOW = block.timestamp; if(NOW >= nextFloorRaisingTime){ if(firstBump){ firstBump = false; floorPrice = floorPrice * 5; }else{ floorPrice = floorPrice * 3; } nextFloorRaisingTime += 300 * 86400; } uint cost = floorPrice*amount/$; require( mvt5xHodlPool >= cost && cost > 0 ); mvt5xHodlPool -= cost; MVT_to_rollout += amount; emit Sell_MVT(amount, cost); (bool success, ) = sender.call{value:cost}(""); require(success, "Transfer failed."); } mapping(uint => mapping(address => uint)) public shares; mapping(uint => uint) public totalShares; mapping(uint => uint) earningsPer; mapping(uint => mapping(address => uint)) payouts; mapping(uint => mapping(address => uint)) public earnings; uint256 constant scaleFactor = 0x10000000000000000; uint constant ETHpool = 0; uint constant MVTpool = 1; uint constant COLORpool = 2; function withdraw(uint pool) public{ address payable sender = payable(msg.sender); require(pool>=0 && pool<=2); if(pool == COLORpool){ update(ETHpool, sender); }else{ update(pool, sender); } uint earned = earnings[pool][sender]; earnings[pool][sender] = 0; require(earned > 0); if(pool == ETHpool){ (bool success, ) = sender.call{value:earned}(""); require(success, "Transfer failed."); }else if(pool == MVTpool){ MVT.transfer(sender, earned); }else if(pool == COLORpool){ COLOR.transfer(sender, earned); } } function addShares(uint pool, address account, uint amount) internal{ update(pool, account); totalShares[pool] += amount; shares[pool][account] += amount; } function removeShares(uint pool, address account, uint amount) internal{ update(pool, account); totalShares[pool] -= amount; shares[pool][account] -= amount; } function dividendsOf(uint pool, address account) public view returns(uint){ uint owedPerShare = earningsPer[pool] - payouts[pool][account]; return shares[pool][account] * owedPerShare / scaleFactor; } function colorDividendsOf(address account) public view returns(uint){ uint owedPerShare = earningsPer[COLORpool] - payouts[COLORpool][account]; return shares[ETHpool][account] * owedPerShare / scaleFactor; } function update(uint pool, address account) internal { uint newMoney = dividendsOf(pool, account); payouts[pool][account] = earningsPer[pool]; earnings[pool][account] += newMoney; if(pool == ETHpool){ newMoney = colorDividendsOf(account); payouts[COLORpool][account] = earningsPer[COLORpool]; earnings[COLORpool][account] += newMoney; } } event PayEthToAcreStakers(uint amount); function payEthToAcreStakers() payable public{ uint val = msg.value; require(totalShares[ETHpool]>0); earningsPer[ETHpool] += val * scaleFactor / totalShares[ETHpool]; emit PayEthToAcreStakers(val); } event PayColor( uint amount ); function tokenFallback(address from, uint value, bytes calldata _data) external{ if(msg.sender == address(COLOR) ){ require(totalShares[ETHpool]>0); earningsPer[COLORpool] += value * scaleFactor / totalShares[ETHpool]; emit PayColor(value); }else{ revert("no want"); } } mapping(uint => uint) public builder_shares; uint public builder_totalShares; uint builder_earningsPer; mapping(uint => uint) builder_payouts; mapping(uint => uint) public builder_earnings; function builder_addShares(uint TOTEM, uint amount) internal{ if(!totemManifest[TOTEM]){ builder_update(TOTEM); builder_totalShares += amount; builder_shares[TOTEM] += amount; } } function builder_removeShares(uint TOTEM, uint amount) internal{ if(!totemManifest[TOTEM]){ builder_update(TOTEM); builder_totalShares -= amount; builder_shares[TOTEM] -= amount; } } function builder_dividendsOf(uint TOTEM) public view returns(uint){ uint owedPerShare = builder_earningsPer - builder_payouts[TOTEM]; return builder_shares[TOTEM] * owedPerShare / scaleFactor; } function builder_update(uint TOTEM) internal{ uint newMoney = builder_dividendsOf(TOTEM); builder_payouts[TOTEM] = builder_earningsPer; builder_earnings[TOTEM] += newMoney; } uint MVT_to_rollout; uint lastRollout; event DepositMVTForRewards(address addr, uint amount); function depositMVTForRewards(uint amount) public{ require(MVT.transferFrom(msg.sender, THIS, amount)); storeUpCommunityRewards(amount); emit DepositMVTForRewards(msg.sender, amount); } function storeUpCommunityRewards(uint amount)internal{ if( builder_totalShares == 0 ){ storedUpBuilderMVT += amount; }else{ builder_earningsPer += ( amount + storedUpBuilderMVT ) * scaleFactor / builder_totalShares; storedUpBuilderMVT = 0; } } event RolloutDepositedMVTRewards(uint amountToDistribute); function rolloutDepositedMVTRewards() public{ uint NOW = block.timestamp; if( (NOW - lastRollout) > 86400 && totalShares[MVTpool] > 0 && MVT_to_rollout > 0){ lastRollout = NOW; uint amountToDistribute = MVT_to_rollout * (totalTotemWeight-totalShares[MVTpool]) / _totalSupply; MVT_to_rollout -= amountToDistribute; earningsPer[MVTpool] += amountToDistribute * scaleFactor / totalShares[MVTpool]; emit RolloutDepositedMVTRewards(amountToDistribute); } } string public name = "Acre"; string public symbol = "ACRE"; uint8 constant public decimals = 18; mapping(address => uint256) public balances; uint _totalSupply; mapping(address => mapping(address => uint)) approvals; event Transfer( address indexed from, address indexed to, uint256 amount, bytes data ); event Transfer( address indexed from, address indexed to, uint256 amount ); event Mint( address indexed addr, uint256 amount ); function mint(address _address, uint _value) internal{ balances[_address] += _value; _totalSupply += _value; if(!isContract(_address)) addShares(ETHpool, _address, _value); emit Mint(_address, _value); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint _value) public virtual returns (bool) { bytes memory empty; return transferToAddress(_to, _value, empty); } function transfer(address _to, uint _value, bytes memory _data) public virtual returns (bool) { if( isContract(_to) ){ return transferToContract(_to, _value, _data); }else{ return transferToAddress(_to, _value, _data); } } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool) { moveTokens(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool) { moveTokens(msg.sender, _to, _value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } function moveTokens(address _from, address _to, uint _amount) internal virtual{ require( _amount <= balances[_from] ); //update balances balances[_from] -= _amount; balances[_to] += _amount; if( !isContract(_from) ){ if(_to != THIS ){ require( MVT.transferFrom(_from, THIS, _amount) ); storeUpCommunityRewards(_amount); } removeShares(ETHpool, _from, _amount); } if(!isContract(_to)) addShares(ETHpool, _to, _amount); emit Transfer(_from, _to, _amount); } function allowance(address src, address guy) public view returns (uint) { return approvals[src][guy]; } function transferFrom(address src, address dst, uint amount) public returns (bool){ address sender = msg.sender; require(approvals[src][sender] >= amount); require(balances[src] >= amount); approvals[src][sender] -= amount; moveTokens(src,dst,amount); bytes memory empty; emit Transfer(sender, dst, amount, empty); return true; } event Approval(address indexed src, address indexed guy, uint amount); function approve(address guy, uint amount) public returns (bool) { address sender = msg.sender; approvals[sender][guy] = amount; emit Approval( sender, guy, amount ); return true; } function isContract(address _addr) public view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; }else { return false; } } uint NFTcount; mapping(address => uint[]) public totemsHad; mapping(address => mapping(uint => bool)) public alreadyHadAtleastOnce; uint totalTotemWeight; event AcreToTotem(address account, uint amount, bool autoStake); function acreToTotem(uint amount, bool autoStake) public returns(uint TOTEM_ID){ address sender = msg.sender; require( MDT.transferFrom(sender, THIS, $) ); totemNFT.mintUniqueTokenTo(autoStake?THIS:sender, NFTcount, amount); if(autoStake){ stakeNFT(sender, NFTcount); }else{ builder_addShares(NFTcount, amount); totemsHad[sender].push(NFTcount); alreadyHadAtleastOnce[sender][NFTcount] = true; } NFTcount += 1; totalTotemWeight += amount; moveTokens(sender, THIS, amount); bytes memory empty; emit Transfer(sender, THIS, amount, empty); emit AcreToTotem(sender, amount, autoStake); return NFTcount - 1; } uint storedUpBuilderMVT; event TotemToMDT(address lastOwner, uint totemID, bool preventBurn); mapping(uint => bool) totemManifest; function totemToMDT(uint totemID, bool preventBurn) public{ address sender = msg.sender; require( sender == staker[totemID] && !totemManifest[totemID] && !requestLocked[totemID]); require( MDT.transfer(sender, $) ); uint totemWeight = totemNFT.getWeight(totemID); removeShares( MVTpool, sender, totemWeight ); staker[totemID] = address(0); uint burnage; if(preventBurn){ require( MVT.transferFrom(sender,THIS, totemWeight) ); storeUpCommunityRewards(totemWeight); }else{ burnage = totemWeight * totalTotemWeight / _totalSupply; } storeUpCommunityRewards(builder_dividendsOf(totemID)+builder_earnings[totemID]); moveTokens(THIS, sender, totemWeight - burnage); _totalSupply -= burnage; balances[THIS] -= burnage; totalTotemWeight -= totemWeight; emit TotemToMDT(sender, totemID, preventBurn); } mapping(uint => address) public staker; event StakeNFT(address who, uint tokenID); function stakeNFT(address who, uint256 tokenID) internal{ staker[tokenID] = who; if( !alreadyHadAtleastOnce[who][tokenID] ){ totemsHad[who].push(tokenID); alreadyHadAtleastOnce[who][tokenID] = true; } addShares( MVTpool, who, totemNFT.getWeight(tokenID) ); emit StakeNFT(who, tokenID); } event UnstakeNFT(address unstaker, uint tokenID); function unstakeNFT(uint tokenID) public{ address sender = msg.sender; require(staker[tokenID] == sender && !requestLocked[tokenID]); uint weight = totemNFT.getWeight(tokenID); removeShares( MVTpool, sender, weight ); staker[tokenID] = address(0); builder_addShares(tokenID, weight); totemNFT.transferFrom(THIS, sender, tokenID); emit UnstakeNFT(sender, tokenID); } function viewTotems(address account, uint[] memory totems) public view returns(uint[] memory tokenIDs, bool[] memory accountIsCurrentlyStaking, uint[] memory acreWeight, bool[] memory owned, bool[] memory manifested, bool[] memory staked, uint[] memory manifestEarnings,bool[] memory pendingManifest,address[] memory holder ){ uint L; if(totems.length==0){ L = totemsHad[account].length; }else{ L = totems.length; } tokenIDs = new uint[](L); acreWeight = new uint[](L); accountIsCurrentlyStaking = new bool[](L); owned = new bool[](L); manifested = new bool[](L); staked = new bool[](L); pendingManifest = new bool[](L); manifestEarnings = new uint[](L); holder = new address[](L); uint tID; for(uint c = 0; c<L; c+=1){ if(totems.length==0){ tID = totemsHad[account][c]; }else{ tID = totems[c]; } tokenIDs[c] = tID; acreWeight[c] = totemNFT.getWeight(tID); accountIsCurrentlyStaking[c] = staker[tID] == account; staked[c] = totemNFT.ownerOf(tID) == THIS; manifested[c] = totemManifest[tID]; pendingManifest[c] = requestLocked[tID]; manifestEarnings[c] = builder_dividendsOf(tID)+builder_earnings[tID]; owned[c] = ( staker[tID] == account || totemNFT.ownerOf(tID) == account ); holder[c] = totemNFT.ownerOf(tID); } } function onERC721Received(address from, uint256 tokenID, bytes memory _data) external returns(bytes4) { bytes4 empty; require( msg.sender == address(totemNFT) ); builder_removeShares(tokenID, totemNFT.getWeight(tokenID) ); stakeNFT(from, tokenID); return empty; } mapping(uint=>address) public theWork; //noita mapping(uint=>uint) workingTotem; mapping(uint=>string) public txt; mapping(uint=>bool) requestLocked; event OracleRequest(address buidlr, uint totemID, uint earningsToManifest, address _theWork, string text, uint ticketID); function oracleRequest(uint totemID, string memory _txt, address contract_optional) public payable returns(uint ticketID){ address sender = msg.sender; require( staker[totemID] == sender && !totemManifest[totemID] && !requestLocked[totemID] ); uint ID = ORACLE.fileRequestTicket{value: msg.value}(1, true); workingTotem[ID] = totemID; theWork[totemID] = contract_optional; txt[totemID] = _txt; requestLocked[totemID] = true; emit OracleRequest(sender, totemID, builder_dividendsOf(totemID)+builder_earnings[totemID], contract_optional, _txt, ID); return ID; } event CommunityReward(address buidlr, uint totemID, uint reward, address contractBuilt, string text, uint ticketID); event RequestRejected(uint totemID, uint ticketID); function oracleIntFallback(uint ticketID, bool requestRejected, uint numberOfOptions, uint[] memory optionWeights, int[] memory intOptions) public{ uint optWeight; uint positive; uint negative; uint totemID = workingTotem[ticketID]; require( msg.sender == address(ORACLE) ); for(uint i; i < numberOfOptions; i+=1){ optWeight = optionWeights[i]; if(intOptions[i]>0){ positive += optWeight; }else{ negative += optWeight; } } if(!requestRejected && positive>negative){ //emit event and give reward if(!totemManifest[totemID]){ totemManifest[totemID] = true; uint earned = builder_earnings[totemID]; if(earned>0){ if( staker[totemID]==address(0) ){ storeUpCommunityRewards(earned); }else{ earnings[MVTpool][staker[totemID]] += earned; } } emit CommunityReward(staker[totemID], totemID, earned, theWork[totemID], txt[totemID], ticketID ); } }else{ emit RequestRejected(totemID,ticketID); } requestLocked[totemID] = false; } } abstract contract Oracle{ function fileRequestTicket( uint8 returnType, bool subjective) public virtual payable returns(uint ticketID); } abstract contract ERC20{ function totalSupply() external virtual view returns (uint256); function balanceOf(address account) external virtual view returns (uint256); function allowance(address owner, address spender) external virtual view returns (uint256); function transfer(address recipient, uint256 amount) external virtual returns (bool); function approve(address spender, uint256 amount) external virtual returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external virtual returns (bool); } contract Totem is ERC721 { constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) { greenpoint = msg.sender; } address greenpoint; mapping(uint => uint) weight; function mintUniqueTokenTo( address _to, uint256 _tokenId, uint _weight ) public { require(msg.sender == greenpoint); super._mint(_to, _tokenId); weight[_tokenId] = _weight; } function getWeight(uint ID) public view returns(uint){ return weight[ID]; } function _baseURI() internal override pure returns (string memory) { return "TOTEM:"; } } abstract contract ERC223ReceivingContract{ function tokenFallback(address _from, uint _value, bytes calldata _data) external virtual; }
* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping (uint256 => address) private _owners; mapping (address => uint256) private _balances; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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"); } 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); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } 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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { IERC721Receiver(to).onERC721Received(from, tokenId, _data); } return true; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { IERC721Receiver(to).onERC721Received(from, tokenId, _data); } return true; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
2,271,479
[ 1, 5787, 6912, 2710, 16, 1496, 486, 6508, 326, 6057, 25121, 2710, 16, 1492, 353, 2319, 18190, 487, 288, 654, 39, 27, 5340, 3572, 25121, 5496, 19, 3155, 508, 3155, 3273, 9408, 628, 1147, 1599, 358, 3410, 1758, 9408, 3410, 1758, 358, 1147, 1056, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 995, 414, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 654, 39, 28275, 16, 467, 654, 39, 28275, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2934, 5831, 548, 203, 5411, 747, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2277, 2934, 5831, 548, 203, 5411, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 2 ]
./full_match/80001/0x4444572f8e6FB8b76f2943C1ba15f5aA9b38eC72/sources/gist-4c970e79d3a27a9edbbf04d6c737be27/Errors.sol
* @title Errors library @author Aave @notice Defines the error messages emitted by the different contracts of the Aave protocol/
library Errors { pragma solidity ^0.8.0; }
5,658,488
[ 1, 4229, 5313, 225, 432, 836, 225, 18003, 281, 326, 555, 2743, 17826, 635, 326, 3775, 20092, 434, 326, 432, 836, 1771, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 9372, 288, 203, 21281, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter; */ library Counters { 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 { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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 (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); } } } } // 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/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 (last updated v4.5.0) (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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 {} /** * @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. * - `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 tokenId ) internal virtual {} } // File: Ai_Karens.sol pragma solidity ^0.8.2; contract nfttest is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = "ipfs://QmPfFUGpHGkZiaNJ6gdTSvbFUomZHYm6o6zxa49zApW1kh/"; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.01 ether; uint256 public maxSupply = 500; uint256 public maxMintAmountPerTx = 5; bool public paused = false; bool public revealed = false; constructor() ERC721("Ai Karens", "KARENS") { setHiddenMetadataUri("ipfs://QmPfFUGpHGkZiaNJ6gdTSvbFUomZHYm6o6zxa49zApW1kh/"); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(supply.current() < 100) { require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); _mintLoop(msg.sender, _mintAmount); } else{ require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } } function total_nft(address _buyer) public view returns (uint256) { uint256[] memory _num = walletOfOwner(_buyer); return _num.length; } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory){ require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function totalSupply() public view returns (uint256) { return supply.current(); } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function withdraw() public onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
File: Ai_Karens.sol
contract nfttest is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.01 ether; uint256 public maxSupply = 500; uint256 public maxMintAmountPerTx = 5; bool public paused = false; bool public revealed = false; function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.2; constructor() ERC721("Ai Karens", "KARENS") { } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(supply.current() < 100) { require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); _mintLoop(msg.sender, _mintAmount); } else{ require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(supply.current() < 100) { require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); _mintLoop(msg.sender, _mintAmount); } else{ require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(supply.current() < 100) { require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); _mintLoop(msg.sender, _mintAmount); } else{ require(total_nft(msg.sender) < 10, "NFT Per Wallet Limit Exceeds!!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } } function total_nft(address _buyer) public view returns (uint256) { uint256[] memory _num = walletOfOwner(_buyer); return _num.length; } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory){ require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory){ require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function totalSupply() public view returns (uint256) { return supply.current(); } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function withdraw() public onlyOwner { require(os); } (bool os, ) = payable(owner()).call{value: address(this).balance}(""); }
10,017,675
[ 1, 812, 30, 432, 77, 67, 47, 21660, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13958, 748, 395, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 565, 533, 1071, 2003, 5791, 273, 3552, 1977, 14432, 203, 565, 533, 1071, 5949, 2277, 3006, 31, 203, 203, 565, 2254, 5034, 1071, 6991, 273, 374, 18, 1611, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 6604, 31, 203, 565, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4188, 273, 1381, 31, 203, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 565, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 203, 203, 203, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 37, 77, 1475, 21660, 3113, 315, 47, 9332, 3156, 7923, 288, 203, 565, 289, 203, 203, 377, 9606, 312, 474, 16687, 12, 11890, 5034, 389, 81, 474, 6275, 13, 288, 203, 3639, 2583, 24899, 81, 474, 6275, 405, 374, 597, 389, 81, 474, 6275, 1648, 943, 49, 474, 6275, 2173, 4188, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-15 */ // Sources flattened with hardhat v2.8.0 https://hardhat.org // File contracts/interfaces/IUniswapV3Factory.sol // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); } // File contracts/interfaces/IUniswapV3Pool.sol interface IUniswapV3Pool { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext( uint16 observationCardinalityNext ) external; /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns ( int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s ); } // File contracts/libraries/Ownable.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 { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(msg.sender); } /** * @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() == msg.sender, "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 contracts/interfaces/IERC20.sol 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 ); } // File contracts/libraries/ERC20.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 IERC20 { 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}. * * 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_, uint8 decimals_ ) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 returns (uint8) { return _decimals; } /** * @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(msg.sender, 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}. * * 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) { _approve(msg.sender, 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: * * - `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) { uint256 currentAllowance = _allowances[sender][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } } _transfer(sender, recipient, 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( msg.sender, spender, _allowances[msg.sender][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[msg.sender][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(msg.sender, 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/libraries/Math.sol library Math { function compound(uint256 rewardRateX96, uint256 nCompounds) internal pure returns (uint256 compoundedX96) { if (nCompounds == 0) { compoundedX96 = 2**96; } else if (nCompounds == 1) { compoundedX96 = rewardRateX96; } else { compoundedX96 = compound(rewardRateX96, nCompounds / 2); compoundedX96 = mulX96(compoundedX96, compoundedX96); if (nCompounds % 2 == 1) { compoundedX96 = mulX96(compoundedX96, rewardRateX96); } } } // ref: https://blogs.sas.com/content/iml/2016/05/16/babylonian-square-roots.html function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function mulX96(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * y) >> 96; } function divX96(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x << 96) / y; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File contracts/libraries/TickMath.sol /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(int256(MAX_TICK)), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require( sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R" ); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24( (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128 ); int24 tickHi = int24( (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128 ); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // File contracts/Const.sol int24 constant INITIAL_QLT_PRICE_TICK = -23000; // QLT_USDC price ~ 100.0 // initial values uint24 constant UNISWAP_POOL_FEE = 10000; int24 constant UNISWAP_POOL_TICK_SPACING = 200; uint16 constant UNISWAP_POOL_OBSERVATION_CADINALITY = 64; // default values uint256 constant DEFAULT_MIN_MINT_PRICE_X96 = 100 * Q96; uint32 constant DEFAULT_TWAP_DURATION = 1 hours; uint32 constant DEFAULT_UNSTAKE_LOCKUP_PERIOD = 3 days; // floating point math uint256 constant Q96 = 2**96; uint256 constant MX96 = Q96 / 10**6; uint256 constant TX96 = Q96 / 10**12; // ERC-20 contract addresses address constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address constant USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); address constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant BUSD = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53); address constant FRAX = address(0x853d955aCEf822Db058eb8505911ED77F175b99e); address constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // Uniswap, see `https://docs.uniswap.org/protocol/reference/deployments` address constant UNISWAP_FACTORY = address( 0x1F98431c8aD98523631AE4a59f267346ea31F984 ); address constant UNISWAP_ROUTER = address( 0xE592427A0AEce92De3Edee1F18E0157C05861564 ); address constant UNISWAP_NFP_MGR = address( 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 ); // File contracts/QLT.sol contract QLT is ERC20, Ownable { event Mint(address indexed account, uint256 amount); event Burn(uint256 amount); mapping(address => bool) public authorizedMinters; constructor() ERC20("Quantland", "QLT", 9) { require( address(this) < USDC, "QLT contract address must be smaller than USDC token contract address" ); authorizedMinters[msg.sender] = true; // deploy uniswap pool IUniswapV3Pool pool = IUniswapV3Pool( IUniswapV3Factory(UNISWAP_FACTORY).createPool( address(this), USDC, UNISWAP_POOL_FEE ) ); pool.initialize(TickMath.getSqrtRatioAtTick(INITIAL_QLT_PRICE_TICK)); pool.increaseObservationCardinalityNext( UNISWAP_POOL_OBSERVATION_CADINALITY ); } function mint(address account, uint256 amount) external onlyAuthorizedMinter { _mint(account, amount); emit Mint(account, amount); } function burn(uint256 amount) external onlyOwner { _burn(msg.sender, amount); emit Burn(amount); } /* Access Control */ modifier onlyAuthorizedMinter() { require(authorizedMinters[msg.sender], "not authorized minter"); _; } function addAuthorizedMinter(address account) external onlyOwner { authorizedMinters[account] = true; } function removeAuthorizedMinter(address account) external onlyOwner { authorizedMinters[account] = false; } }
@dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) @notice Calculates sqrt(1.0001^tick) * 2^96 @dev Throws if |tick| > max tick @param tick The input tick for the above formula @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) at the given tick this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. we then downcast because we know the result always fits within 160 bits due to our tick input constraint we round up in the division so getTickAtSqrtRatio of the output price is always consistent
{ uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(int256(MAX_TICK)), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); }
7,639,292
[ 1, 1986, 5224, 4024, 716, 2026, 506, 2275, 358, 1322, 85, 3797, 8541, 861, 6264, 8470, 628, 613, 1026, 404, 18, 13304, 434, 576, 17, 10392, 225, 1021, 4207, 4024, 716, 2026, 506, 2275, 358, 1322, 85, 3797, 8541, 861, 6264, 8470, 628, 613, 1026, 404, 18, 13304, 434, 576, 10392, 225, 1021, 5224, 460, 716, 848, 506, 2106, 628, 1322, 85, 3797, 8541, 861, 6264, 18, 31208, 358, 1322, 85, 3797, 8541, 861, 6264, 12, 6236, 67, 56, 16656, 13, 225, 1021, 4207, 460, 716, 848, 506, 2106, 628, 1322, 85, 3797, 8541, 861, 6264, 18, 31208, 358, 1322, 85, 3797, 8541, 861, 6264, 12, 6694, 67, 56, 16656, 13, 225, 26128, 5700, 12, 21, 18, 13304, 66, 6470, 13, 225, 576, 66, 10525, 225, 22435, 309, 571, 6470, 96, 405, 943, 4024, 225, 4024, 1021, 810, 4024, 364, 326, 5721, 8013, 327, 5700, 5147, 60, 10525, 432, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 288, 203, 3639, 2254, 5034, 2417, 6264, 273, 4024, 411, 374, 203, 5411, 692, 2254, 5034, 19236, 474, 5034, 12, 6470, 3719, 203, 5411, 294, 2254, 5034, 12, 474, 5034, 12, 6470, 10019, 203, 3639, 2583, 12, 5113, 6264, 1648, 2254, 5034, 12, 474, 5034, 12, 6694, 67, 56, 16656, 13, 3631, 315, 56, 8863, 203, 203, 3639, 2254, 5034, 7169, 273, 2417, 6264, 473, 374, 92, 21, 480, 374, 203, 5411, 692, 374, 5297, 7142, 70, 29, 3707, 16410, 26, 74, 361, 6418, 7598, 22, 72, 30042, 72, 21, 69, 6162, 24, 11664, 203, 5411, 294, 374, 92, 21, 12648, 12648, 12648, 12648, 31, 203, 3639, 309, 261, 5113, 6264, 473, 374, 92, 22, 480, 374, 13, 203, 5411, 7169, 273, 261, 9847, 380, 374, 5297, 74, 10580, 5324, 4366, 9036, 72, 9803, 1578, 6162, 69, 8749, 2733, 6260, 3672, 73, 22, 3437, 69, 13, 1671, 8038, 31, 203, 3639, 309, 261, 5113, 6264, 473, 374, 92, 24, 480, 374, 13, 203, 5411, 7169, 273, 261, 9847, 380, 374, 5297, 74, 22, 73, 3361, 74, 25, 74, 26, 4313, 29, 1578, 10241, 2138, 4763, 27, 8522, 23, 71, 27, 8313, 952, 13, 1671, 8038, 31, 203, 3639, 309, 261, 5113, 6264, 473, 374, 92, 28, 480, 374, 13, 203, 5411, 7169, 273, 261, 9847, 380, 374, 5297, 73, 25, 71, 1077, 69, 27, 73, 2163, 73, 24, 73, 9498, 71, 5718, 3247, 73, 7598, 5908, 9803, 4315, 20, 13, 1671, 8038, 31, 203, 3639, 309, 261, 5113, 6264, 473, 374, 92, 2163, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/INFTComplexGemPoolData.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/INFTComplexGemPool.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../libs/AddressSet.sol"; library ComplexPoolLib { using AddressSet for AddressSet.Set; /** * @dev Event generated when an NFT claim is created using base currency */ event NFTGemClaimCreated( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 length, uint256 quantity, uint256 amountPaid ); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 amountPaid, uint256 quantity, uint256 feeAssessed ); /** * @dev Event generated when an NFT erc20 claim is redeemed */ event NFTGemERC20ClaimRedeemed( address indexed account, address indexed pool, uint256 indexed claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 quantity, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated( address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity ); /** * @dev data describes complex pool */ struct ComplexPoolData { // governor and multitoken target address pool; address multitoken; address governor; address feeTracker; address swapHelper; uint256 category; bool visible; // it all starts with a symbol and a nams string symbol; string name; string description; // magic economy numbers uint256 ethPrice; uint256 minTime; uint256 maxTime; uint256 diffstep; uint256 maxClaims; uint256 maxQuantityPerClaim; uint256 maxClaimsPerAccount; bool validateerc20; bool allowPurchase; bool enabled; INFTComplexGemPoolData.PriceIncrementType priceIncrementType; mapping(uint256 => INFTGemMultiToken.TokenType) tokenTypes; mapping(uint256 => uint256) tokenIds; mapping(uint256 => address) tokenSources; AddressSet.Set allowedTokenSources; uint256[] tokenHashes; // next ids of things uint256 nextGemIdVal; uint256 nextClaimIdVal; uint256 totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) claimLockTimestamps; mapping(uint256 => address) claimLockToken; mapping(uint256 => uint256) claimAmountPaid; mapping(uint256 => uint256) claimQuant; mapping(uint256 => uint256) claimTokenAmountPaid; mapping(uint256 => mapping(address => uint256)) importedLegacyToken; // input NFTs storage mapping(uint256 => uint256) gemClaims; mapping(uint256 => uint256[]) claimIds; mapping(uint256 => uint256[]) claimQuantities; mapping(address => bool) controllers; mapping(address => uint256) claimsMade; INFTComplexGemPoolData.InputRequirement[] inputRequirements; AddressSet.Set allowedTokens; } function checkGemRequirement( ComplexPoolData storage self, uint256 _inputIndex, address _holderAddress, uint256 _quantity ) internal view returns (address) { address gemtoken; int256 required = int256( self.inputRequirements[_inputIndex].minVal * _quantity ); uint256[] memory hashes = INFTGemMultiToken( self.inputRequirements[_inputIndex].token ).heldTokens(_holderAddress); for ( uint256 _hashIndex = 0; _hashIndex < hashes.length; _hashIndex += 1 ) { uint256 hashAt = hashes[_hashIndex]; if ( INFTComplexGemPoolData(self.inputRequirements[_inputIndex].pool) .tokenType(hashAt) == INFTGemMultiToken.TokenType.GEM ) { gemtoken = self.inputRequirements[_inputIndex].token; uint256 balance = IERC1155( self.inputRequirements[_inputIndex].token ).balanceOf(_holderAddress, hashAt); if (balance > uint256(required)) { balance = uint256(required); } if (balance == 0) { continue; } required = required - int256(balance); } if ( required == 0 && self.inputRequirements[_inputIndex].exactAmount == false ) { break; } if (required < 0) { require(required == 0, "EXACT_AMOUNT_REQUIRED"); } } require(required == 0, "UNMET_GEM_REQUIREMENT"); return gemtoken; } /** * @dev checks to see that account owns all the pool requirements needed to mint at least the given quantity of NFT */ function requireInputReqs( ComplexPoolData storage self, address _holderAddress, uint256 _quantity ) public view { for ( uint256 _inputIndex = 0; _inputIndex < self.inputRequirements.length; _inputIndex += 1 ) { if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC20 ) { require( IERC20(self.inputRequirements[_inputIndex].token).balanceOf( _holderAddress ) >= self.inputRequirements[_inputIndex].minVal * (_quantity), "UNMET_ERC20_REQUIREMENT" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC1155 ) { require( IERC1155(self.inputRequirements[_inputIndex].token) .balanceOf( _holderAddress, self.inputRequirements[_inputIndex].tokenId ) >= self.inputRequirements[_inputIndex].minVal * (_quantity), "UNMET_ERC1155_REQUIREMENT" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.POOL ) { checkGemRequirement( self, _inputIndex, _holderAddress, _quantity ); } } } /** * @dev Transfer a quantity of input reqs from to */ function takeInputReqsFrom( ComplexPoolData storage self, uint256 _claimHash, address _fromAddress, uint256 _quantity ) internal { address gemtoken; for ( uint256 _inputIndex = 0; _inputIndex < self.inputRequirements.length; _inputIndex += 1 ) { if (!self.inputRequirements[_inputIndex].takeCustody) { continue; } if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC20 ) { IERC20 token = IERC20( self.inputRequirements[_inputIndex].token ); token.transferFrom( _fromAddress, self.pool, self.inputRequirements[_inputIndex].minVal * (_quantity) ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC1155 ) { IERC1155 token = IERC1155( self.inputRequirements[_inputIndex].token ); token.safeTransferFrom( _fromAddress, self.pool, self.inputRequirements[_inputIndex].tokenId, self.inputRequirements[_inputIndex].minVal * (_quantity), "" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.POOL ) { gemtoken = checkGemRequirement( self, _inputIndex, _fromAddress, _quantity ); } } if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) { IERC1155(gemtoken).safeBatchTransferFrom( _fromAddress, self.pool, self.claimIds[_claimHash], self.claimQuantities[_claimHash], "" ); } } /** * @dev Return the returnable input requirements for claimhash to account */ function returnInputReqsTo( ComplexPoolData storage self, uint256 _claimHash, address _toAddress, uint256 _quantity ) internal { address gemtoken; for (uint256 i = 0; i < self.inputRequirements.length; i++) { if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.ERC20 && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { IERC20 token = IERC20(self.inputRequirements[i].token); token.transferFrom( self.pool, _toAddress, self.inputRequirements[i].minVal * (_quantity) ); } else if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.ERC1155 && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { IERC1155 token = IERC1155(self.inputRequirements[i].token); token.safeTransferFrom( self.pool, _toAddress, self.inputRequirements[i].tokenId, self.inputRequirements[i].minVal * (_quantity), "" ); } else if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.POOL && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { gemtoken = self.inputRequirements[i].token; } } if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) { IERC1155(gemtoken).safeBatchTransferFrom( self.pool, _toAddress, self.claimIds[_claimHash], self.claimQuantities[_claimHash], "" ); } } /** * @dev add an input requirement for this token */ function addInputRequirement( ComplexPoolData storage self, address token, address pool, INFTComplexGemPool.RequirementType inputType, uint256 tokenId, uint256 minAmount, bool takeCustody, bool burn, bool exactAmount ) public { require(token != address(0), "INVALID_TOKEN"); require( inputType == INFTComplexGemPool.RequirementType.ERC20 || inputType == INFTComplexGemPool.RequirementType.ERC1155 || inputType == INFTComplexGemPool.RequirementType.POOL, "INVALID_INPUTTYPE" ); require( (inputType == INFTComplexGemPool.RequirementType.POOL && pool != address(0)) || inputType != INFTComplexGemPool.RequirementType.POOL, "INVALID_POOL" ); require( (inputType == INFTComplexGemPool.RequirementType.ERC20 && tokenId == 0) || inputType == INFTComplexGemPool.RequirementType.ERC1155 || (inputType == INFTComplexGemPool.RequirementType.POOL && tokenId == 0), "INVALID_TOKENID" ); require(minAmount != 0, "ZERO_AMOUNT"); require(!(!takeCustody && burn), "INVALID_TOKENSTATE"); self.inputRequirements.push( INFTComplexGemPoolData.InputRequirement( token, pool, inputType, tokenId, minAmount, takeCustody, burn, exactAmount ) ); } /** * @dev update input requirement at index */ function updateInputRequirement( ComplexPoolData storage self, uint256 _index, address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputRequirementType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) public { require(_index < self.inputRequirements.length, "OUT_OF_RANGE"); require(_tokenAddress != address(0), "INVALID_TOKEN"); require( _inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 || _inputRequirementType == INFTComplexGemPool.RequirementType.ERC1155 || _inputRequirementType == INFTComplexGemPool.RequirementType.POOL, "INVALID_INPUTTYPE" ); require( (_inputRequirementType == INFTComplexGemPool.RequirementType.POOL && _poolAddress != address(0)) || _inputRequirementType != INFTComplexGemPool.RequirementType.POOL, "INVALID_POOL" ); require( (_inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 && _tokenId == 0) || _inputRequirementType == INFTComplexGemPool.RequirementType.ERC1155 || (_inputRequirementType == INFTComplexGemPool.RequirementType.POOL && _tokenId == 0), "INVALID_TOKENID" ); require(_minAmount != 0, "ZERO_AMOUNT"); require(!(!_takeCustody && _burn), "INVALID_TOKENSTATE"); self.inputRequirements[_index] = INFTComplexGemPoolData .InputRequirement( _tokenAddress, _poolAddress, _inputRequirementType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev count of input requirements */ function allInputRequirementsLength(ComplexPoolData storage self) public view returns (uint256) { return self.inputRequirements.length; } /** * @dev input requirements at index */ function allInputRequirements(ComplexPoolData storage self, uint256 _index) public view returns ( address, address, INFTComplexGemPool.RequirementType, uint256, uint256, bool, bool, bool ) { require(_index < self.inputRequirements.length, "OUT_OF_RANGE"); INFTComplexGemPoolData.InputRequirement memory req = self .inputRequirements[_index]; return ( req.token, req.pool, req.inputType, req.tokenId, req.minVal, req.takeCustody, req.burn, req.exactAmount ); } /** * @dev attempt to create a claim using the given timeframe with count */ function createClaims( ComplexPoolData storage self, uint256 _timeframe, uint256 _count ) public { // enabled require(self.enabled == true, "DISABLED"); // minimum timeframe require(_timeframe >= self.minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(_count != 0, "ZERO_QUANTITY"); // maximum timeframe require( (self.maxTime != 0 && _timeframe <= self.maxTime) || self.maxTime == 0, "TIMEFRAME_TOO_LONG" ); // max quantity per claim require( (self.maxQuantityPerClaim != 0 && _count <= self.maxQuantityPerClaim) || self.maxQuantityPerClaim == 0, "MAX_QUANTITY_EXCEEDED" ); require( (self.maxClaimsPerAccount != 0 && self.claimsMade[msg.sender] < self.maxClaimsPerAccount) || self.maxClaimsPerAccount == 0, "MAX_QUANTITY_EXCEEDED" ); uint256 adjustedBalance = msg.value / (_count); // cost given this timeframe uint256 cost = (self.ethPrice * (self.minTime)) / (_timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = nextClaimHash(self); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // require the user to have the input requirements requireInputReqs(self, msg.sender, _count); // mint the new claim to the caller's address INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1); INFTGemMultiToken(self.multitoken).setTokenData( claimHash, INFTGemMultiToken.TokenType.CLAIM, address(this) ); addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM); // record the claim unlock time and cost paid for this claim uint256 claimUnlockTimestamp = block.timestamp + (_timeframe); self.claimLockTimestamps[claimHash] = claimUnlockTimestamp; self.claimAmountPaid[claimHash] = cost * (_count); self.claimQuant[claimHash] = _count; self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1); // tranasfer NFT input requirements from user to pool takeInputReqsFrom(self, claimHash, msg.sender, _count); // emit an event about it emit NFTGemClaimCreated( msg.sender, address(self.pool), claimHash, _timeframe, _count, cost ); // increase the staked eth balance self.totalStakedEth = self.totalStakedEth + (cost * (_count)); // return the extra to sender if (msg.value > cost * (_count)) { (bool success, ) = payable(msg.sender).call{ value: msg.value - (cost * (_count)) }(""); require(success, "REFUND_FAILED"); } } function getPoolFee(ComplexPoolData storage self, address tokenUsed) internal view returns (uint256) { // get the fee for this pool if it exists uint256 poolDivFeeHash = uint256( keccak256(abi.encodePacked("pool_fee", address(self.pool))) ); uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee( poolDivFeeHash ); // get the pool fee for this token if it exists uint256 poolTokenFeeHash = uint256( keccak256(abi.encodePacked("pool_fee", address(tokenUsed))) ); uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee( poolTokenFeeHash ); // get the default fee amoutn for this token uint256 defaultFeeHash = uint256( keccak256(abi.encodePacked("pool_fee")) ); uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee( defaultFeeHash ); defaultFee = defaultFee == 0 ? 2000 : defaultFee; // get the fee, preferring the token fee if available uint256 feeNum = poolFee != poolTokenFee ? (poolTokenFee != 0 ? poolTokenFee : poolFee) : poolFee; // set the fee to default if it is 0 return feeNum == 0 ? defaultFee : feeNum; } function getMinimumLiquidity( ComplexPoolData storage self, address tokenUsed ) internal view returns (uint256) { // get the fee for this pool if it exists uint256 poolDivFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity", address(self.pool))) ); uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee( poolDivFeeHash ); // get the pool fee for this token if it exists uint256 poolTokenFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity", address(tokenUsed))) ); uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee( poolTokenFeeHash ); // get the default fee amoutn for this token uint256 defaultFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity")) ); uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee( defaultFeeHash ); defaultFee = defaultFee == 0 ? 50 : defaultFee; // get the fee, preferring the token fee if available uint256 feeNum = poolFee != poolTokenFee ? (poolTokenFee != 0 ? poolTokenFee : poolFee) : poolFee; // set the fee to default if it is 0 return feeNum == 0 ? defaultFee : feeNum; } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function createERC20Claims( ComplexPoolData storage self, address erc20token, uint256 tokenAmount, uint256 count ) public { // enabled require(self.enabled == true, "DISABLED"); // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require( (self.allowedTokens.count() > 0 && self.allowedTokens.exists(erc20token)) || self.allowedTokens.count() == 0, "TOKEN_DISALLOWED" ); // zero qty require(count != 0, "ZERO_QUANTITY"); // max quantity per claim require( (self.maxQuantityPerClaim != 0 && count <= self.maxQuantityPerClaim) || self.maxQuantityPerClaim == 0, "MAX_QUANTITY_EXCEEDED" ); require( (self.maxClaimsPerAccount != 0 && self.claimsMade[msg.sender] < self.maxClaimsPerAccount) || self.maxClaimsPerAccount == 0, "MAX_QUANTITY_EXCEEDED" ); // require the user to have the input requirements requireInputReqs(self, msg.sender, count); // Uniswap pool must exist require( ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL" ); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. ( uint256 ethereum, uint256 tokenReserve, uint256 ethReserve ) = ISwapQueryHelper(self.swapHelper).coinQuote( erc20token, tokenAmount / (count) ); // TODO: update liquidity multiple from fee manager if (self.validateerc20 == true) { uint256 minLiquidity = getMinimumLiquidity(self, erc20token); // make sure the convertible amount is has reserves > 100x the token require( ethReserve >= ethereum * minLiquidity * (count), "INSUFFICIENT_ETH_LIQUIDITY" ); // make sure the convertible amount is has reserves > 100x the token require( tokenReserve >= tokenAmount * minLiquidity * (count), "INSUFFICIENT_TOKEN_LIQUIDITY" ); } // make sure the convertible amount is less than max price require(ethereum <= self.ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = (self.ethPrice * (self.minTime)) / (ethereum); // make sure the convertible amount is less than max price require(maturityTime >= self.minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = nextClaimHash(self); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1); INFTGemMultiToken(self.multitoken).setTokenData( claimHash, INFTGemMultiToken.TokenType.CLAIM, address(this) ); addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM); // record the claim unlock time and cost paid for this claim uint256 claimUnlockTimestamp = block.timestamp + (maturityTime); self.claimLockTimestamps[claimHash] = claimUnlockTimestamp; self.claimAmountPaid[claimHash] = ethereum; self.claimLockToken[claimHash] = erc20token; self.claimTokenAmountPaid[claimHash] = tokenAmount; self.claimQuant[claimHash] = count; self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1); // tranasfer NFT input requirements from user to pool takeInputReqsFrom(self, claimHash, msg.sender, count); // increase staked eth amount self.totalStakedEth = self.totalStakedEth + (ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated( msg.sender, address(self.pool), claimHash, maturityTime, erc20token, count, ethereum ); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom( msg.sender, address(self.pool), tokenAmount ); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim( ComplexPoolData storage self, uint256 _claimHash, bool _requireMature ) public { // enabled require(self.enabled == true, "DISABLED"); // check the maturity of the claim - only issue gem if mature uint256 unlockTime = self.claimLockTimestamps[_claimHash]; bool isMature = unlockTime < block.timestamp; require( !_requireMature || (_requireMature && isMature), "IMMATURE_CLAIM" ); __collectClaim(self, _claimHash); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function __collectClaim(ComplexPoolData storage self, uint256 claimHash) internal { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require( IERC1155(self.multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER" ); uint256 unlockTime = self.claimLockTimestamps[claimHash]; uint256 unlockPaid = self.claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = self.claimLockToken[claimHash]; uint256 unlockTokenPaid = self.claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(self.multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { feePortion = unlockTokenPaid / getPoolFee(self, tokenUsed); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom( address(self.pool), self.feeTracker, feePortion ); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom( address(self.pool), msg.sender, unlockTokenPaid - (feePortion) ); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(self.pool), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, self.claimQuant[claimHash], feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { feePortion = unlockPaid / getPoolFee(self, address(0)); } // transfer the ETH fee to fee tracker payable(self.feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid - (feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed( msg.sender, address(self.pool), claimHash, unlockPaid, self.claimQuant[claimHash], feePortion ); } // tranasfer NFT input requirements from pool to user returnInputReqsTo( self, claimHash, msg.sender, self.claimQuant[claimHash] ); // deduct the total staked ETH balance of the pool self.totalStakedEth = self.totalStakedEth - (unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = nextGemHash(self); // associate gem and claim self.gemClaims[nextHash] = claimHash; // mint the gem INFTGemMultiToken(self.multitoken).mint( msg.sender, nextHash, self.claimQuant[claimHash] ); addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated( msg.sender, address(self.pool), claimHash, nextHash, self.claimQuant[claimHash] ); } /** * @dev purchase gem(s) at the listed pool price */ function purchaseGems( ComplexPoolData storage self, address sender, uint256 value, uint256 count ) public { // enabled require(self.enabled == true, "DISABLED"); // non-zero balance require(value != 0, "ZERO_BALANCE"); // non-zero quantity require(count != 0, "ZERO_QUANTITY"); // sufficient input eth uint256 adjustedBalance = value / (count); require(adjustedBalance >= self.ethPrice, "INSUFFICIENT_ETH"); require(self.allowPurchase == true, "PURCHASE_DISALLOWED"); // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = nextGemHash(self); // mint the gem INFTGemMultiToken(self.multitoken).mint(sender, nextHash, count); addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM); // transfer the funds for the gem to the fee tracker payable(self.feeTracker).transfer(value); // emit an event about a gem getting created emit NFTGemCreated(sender, address(self.pool), 0, nextHash, count); } /** * @dev create a token of token hash / token type */ function addToken( ComplexPoolData storage self, uint256 tokenHash, INFTGemMultiToken.TokenType tokenType ) public { require( tokenType == INFTGemMultiToken.TokenType.CLAIM || tokenType == INFTGemMultiToken.TokenType.GEM, "INVALID_TOKENTYPE" ); self.tokenHashes.push(tokenHash); self.tokenTypes[tokenHash] = tokenType; self.tokenIds[tokenHash] = tokenType == INFTGemMultiToken.TokenType.CLAIM ? nextClaimId(self) : nextGemId(self); INFTGemMultiToken(self.multitoken).setTokenData( tokenHash, tokenType, address(this) ); if (tokenType == INFTGemMultiToken.TokenType.GEM) { increaseDifficulty(self); } } /** * @dev get the next claim id */ function nextClaimId(ComplexPoolData storage self) public returns (uint256) { uint256 ncId = self.nextClaimIdVal; self.nextClaimIdVal = self.nextClaimIdVal + (1); return ncId; } /** * @dev get the next gem id */ function nextGemId(ComplexPoolData storage self) public returns (uint256) { uint256 ncId = self.nextGemIdVal; self.nextGemIdVal = self.nextGemIdVal + (1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function increaseDifficulty(ComplexPoolData storage self) public { if ( self.priceIncrementType == INFTComplexGemPoolData.PriceIncrementType.COMPOUND ) { uint256 diffIncrease = self.ethPrice / (self.diffstep); self.ethPrice = self.ethPrice + (diffIncrease); } else if ( self.priceIncrementType == INFTComplexGemPoolData.PriceIncrementType.INVERSELOG ) { uint256 diffIncrease = self.diffstep / (self.ethPrice); self.ethPrice = self.ethPrice + (diffIncrease); } } /** * @dev the hash of the next gem to be minted */ function nextGemHash(ComplexPoolData storage self) public view returns (uint256) { return uint256( keccak256( abi.encodePacked( "gem", address(self.pool), self.nextGemIdVal ) ) ); } /** * @dev the hash of the next claim to be minted */ function nextClaimHash(ComplexPoolData storage self) public view returns (uint256) { return (self.maxClaims != 0 && self.nextClaimIdVal <= self.maxClaims) || self.maxClaims == 0 ? uint256( keccak256( abi.encodePacked( "claim", address(self.pool), self.nextClaimIdVal ) ) ) : 0; } /** * @dev get the token hash at index */ function allTokenHashes(ComplexPoolData storage self, uint256 ndx) public view returns (uint256) { return self.tokenHashes[ndx]; } /** * @dev return the claim amount paid for this claim */ function claimAmount(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim hash */ function claimQuantity(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimQuant[claimHash]; } /** * @dev the lock time for this claim hash. once past lock time a gem is minted */ function claimUnlockTime(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimLockTimestamps[claimHash]; } /** * @dev return the claim token amount for this claim hash */ function claimTokenAmount(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimTokenAmountPaid[claimHash]; } /** * @dev return the claim hash of the given gemhash */ function gemClaimHash(ComplexPoolData storage self, uint256 gemHash) public view returns (uint256) { return self.gemClaims[gemHash]; } /** * @dev return the token that was staked to create the given token hash. 0 if the native token */ function stakedToken(ComplexPoolData storage self, uint256 claimHash) public view returns (address) { return self.claimLockToken[claimHash]; } /** * @dev add a token that is allowed to be used to create a claim */ function addAllowedToken(ComplexPoolData storage self, address token) public { if (!self.allowedTokens.exists(token)) { self.allowedTokens.insert(token); } } /** * @dev remove a token that is allowed to be used to create a claim */ function removeAllowedToken(ComplexPoolData storage self, address token) public { if (self.allowedTokens.exists(token)) { self.allowedTokens.remove(token); } } /** * @dev deposit into pool */ function deposit( ComplexPoolData storage self, address erc20token, uint256 tokenAmount ) public { if (erc20token == address(0)) { require(msg.sender.balance >= tokenAmount, "INSUFFICIENT_BALANCE"); self.totalStakedEth = self.totalStakedEth + (msg.sender.balance); } else { require( IERC20(erc20token).balanceOf(msg.sender) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC20(erc20token).transferFrom( msg.sender, address(self.pool), tokenAmount ); } } /** * @dev deposit NFT into pool */ function depositNFT( ComplexPoolData storage self, address erc1155token, uint256 tokenId, uint256 tokenAmount ) public { require( IERC1155(erc1155token).balanceOf(msg.sender, tokenId) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC1155(erc1155token).safeTransferFrom( msg.sender, address(self.pool), tokenId, tokenAmount, "" ); } /** * @dev withdraw pool contents */ function withdraw( ComplexPoolData storage self, address erc20token, address destination, uint256 tokenAmount ) public { require(destination != address(0), "ZERO_ADDRESS"); require( self.controllers[msg.sender] == true || msg.sender == self.governor, "UNAUTHORIZED" ); if (erc20token == address(0)) { payable(destination).transfer(tokenAmount); } else { IERC20(erc20token).transferFrom( address(self.pool), address(destination), tokenAmount ); } } /** * @dev withdraw pool NFT */ function withdrawNFT( ComplexPoolData storage self, address erc1155token, address destination, uint256 tokenId, uint256 tokenAmount ) public { require( self.controllers[msg.sender] == true || msg.sender == self.governor, "UNAUTHORIZED" ); require(erc1155token != address(0), "ZERO_ADDRESS"); require(destination != address(0), "ZERO_ADDRESS"); require( IERC1155(erc1155token).balanceOf(address(self.pool), tokenId) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC1155(erc1155token).safeTransferFrom( address(self.pool), address(destination), tokenId, tokenAmount, "" ); } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems( ComplexPoolData storage self, address creator, address funder ) public { require(self.multitoken != address(0), "NO_MULTITOKEN"); require( creator != address(0) && funder != address(0), "ZERO_DESTINATION" ); require(self.nextGemIdVal == 0, "ALREADY_MINTED"); uint256 gemHash = nextGemHash(self); INFTGemMultiToken(self.multitoken).mint(creator, gemHash, 1); addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated(creator, address(self.pool), 0, gemHash, 1); gemHash = nextGemHash(self); INFTGemMultiToken(self.multitoken).mint(funder, gemHash, 1); addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated(funder, address(self.pool), 0, gemHash, 1); } }
* @dev input requirements at index/
function allInputRequirements(ComplexPoolData storage self, uint256 _index) public view returns ( address, address, INFTComplexGemPool.RequirementType, uint256, uint256, bool, bool, bool ) { require(_index < self.inputRequirements.length, "OUT_OF_RANGE"); INFTComplexGemPoolData.InputRequirement memory req = self .inputRequirements[_index]; return ( req.token, req.pool, req.inputType, req.tokenId, req.minVal, req.takeCustody, req.burn, req.exactAmount ); }
15,863,446
[ 1, 2630, 8433, 622, 770, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 777, 1210, 15465, 12, 12795, 2864, 751, 2502, 365, 16, 2254, 5034, 389, 1615, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 1758, 16, 203, 5411, 1758, 16, 203, 5411, 2120, 4464, 12795, 43, 351, 2864, 18, 18599, 559, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 1426, 16, 203, 5411, 1426, 16, 203, 5411, 1426, 203, 3639, 262, 203, 565, 288, 203, 3639, 2583, 24899, 1615, 411, 365, 18, 2630, 15465, 18, 2469, 16, 315, 5069, 67, 3932, 67, 15928, 8863, 203, 3639, 2120, 4464, 12795, 43, 351, 2864, 751, 18, 1210, 18599, 3778, 1111, 273, 365, 203, 3639, 263, 2630, 15465, 63, 67, 1615, 15533, 203, 3639, 327, 261, 203, 5411, 1111, 18, 2316, 16, 203, 5411, 1111, 18, 6011, 16, 203, 5411, 1111, 18, 2630, 559, 16, 203, 5411, 1111, 18, 2316, 548, 16, 203, 5411, 1111, 18, 1154, 3053, 16, 203, 5411, 1111, 18, 22188, 39, 641, 973, 16, 203, 5411, 1111, 18, 70, 321, 16, 203, 5411, 1111, 18, 17165, 6275, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract GetsBurned { function () payable { } function BurnMe () { // Selfdestruct and send eth to self, selfdestruct(address(this)); } }
Selfdestruct and send eth to self,
function BurnMe () { selfdestruct(address(this)); }
2,477,791
[ 1, 10084, 5489, 8813, 471, 1366, 13750, 358, 365, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 321, 4667, 1832, 288, 203, 3639, 365, 5489, 8813, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x163F73F63FE61Dc0C52dd1D740a4856E1D414BA4/sources/InitializableAdminUpgradeabilityProxy.sol
* @title InitializableUpgradeabilityProxy @dev Extends BaseUpgradeabilityProxy with an initializer for initializing implementation and init data./
abstract contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } }
16,971,251
[ 1, 4435, 6934, 10784, 2967, 3886, 225, 6419, 5839, 3360, 10784, 2967, 3886, 598, 392, 12562, 364, 22584, 4471, 471, 1208, 501, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 10188, 6934, 10784, 2967, 3886, 353, 3360, 10784, 2967, 3886, 288, 203, 565, 445, 4046, 12, 2867, 389, 28339, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 30810, 1435, 422, 1758, 12, 20, 10019, 203, 3639, 1815, 12, 9883, 7618, 2689, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2668, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 26112, 300, 404, 10019, 203, 3639, 389, 542, 13621, 24899, 28339, 1769, 203, 3639, 309, 24899, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 261, 6430, 2216, 16, 13, 273, 389, 28339, 18, 22216, 1991, 24899, 892, 1769, 203, 5411, 2583, 12, 4768, 1769, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 4046, 12, 2867, 389, 28339, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 30810, 1435, 422, 1758, 12, 20, 10019, 203, 3639, 1815, 12, 9883, 7618, 2689, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2668, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 26112, 300, 404, 10019, 203, 3639, 389, 542, 13621, 24899, 28339, 1769, 203, 3639, 309, 24899, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 261, 6430, 2216, 16, 13, 273, 389, 28339, 18, 22216, 1991, 24899, 892, 1769, 203, 5411, 2583, 12, 4768, 1769, 203, 3639, 289, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x7ea997bFe3f2355b28faad05e7a7C5f77180C43a/sources/contracts/Contract.sol
Transfer DAO tokens from the sender to the contract Wrap Ether into WETH Mint LP tokens and assign them to the sender Transfer DAO tokens from the sender to the contract Transfer SHIB tokens from the sender to the contract Mint LP tokens and assign them to the sender
function addLiquidity(uint256 amount) external { require(amount > 0, "Amount must be greater than zero."); require(balanceOf[msg.sender] >= amount, "Insufficient balance."); if (liquidityAllocation == LiquidityAllocation.WETH) { balanceOf[msg.sender] -= amount; balanceOf[address(this)] += amount; require(success, "WETH deposit failed."); lpTokenSupply += amount; lpTokenBalance[msg.sender] += amount; balanceOf[msg.sender] -= amount; balanceOf[address(this)] += amount; shibToken.safeTransferFrom(msg.sender, address(this), amount); lpTokenSupply += amount; lpTokenBalance[msg.sender] += amount; } }
11,594,768
[ 1, 5912, 463, 20463, 2430, 628, 326, 5793, 358, 326, 6835, 4266, 512, 1136, 1368, 678, 1584, 44, 490, 474, 511, 52, 2430, 471, 2683, 2182, 358, 326, 5793, 12279, 463, 20463, 2430, 628, 326, 5793, 358, 326, 6835, 12279, 6122, 13450, 2430, 628, 326, 5793, 358, 326, 6835, 490, 474, 511, 52, 2430, 471, 2683, 2182, 358, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 6275, 1297, 506, 6802, 2353, 3634, 1199, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 3844, 16, 315, 5048, 11339, 11013, 1199, 1769, 203, 203, 3639, 309, 261, 549, 372, 24237, 17353, 422, 511, 18988, 24237, 17353, 18, 59, 1584, 44, 13, 288, 203, 5411, 11013, 951, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 5411, 11013, 951, 63, 2867, 12, 2211, 25887, 1011, 3844, 31, 203, 203, 5411, 2583, 12, 4768, 16, 315, 59, 1584, 44, 443, 1724, 2535, 1199, 1769, 203, 203, 5411, 12423, 1345, 3088, 1283, 1011, 3844, 31, 203, 5411, 12423, 1345, 13937, 63, 3576, 18, 15330, 65, 1011, 3844, 31, 203, 5411, 11013, 951, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 5411, 11013, 951, 63, 2867, 12, 2211, 25887, 1011, 3844, 31, 203, 203, 5411, 699, 495, 1345, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 203, 5411, 12423, 1345, 3088, 1283, 1011, 3844, 31, 203, 5411, 12423, 1345, 13937, 63, 3576, 18, 15330, 65, 1011, 3844, 31, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x822eAc2cc5D10D31907945ab543B7fCB6E877507/sources/project_/contracts/Cairofinance22.sol
address iBnBToken = 0xd7D069493685A581d27824Fc46EdA46B7EfC0063; address iUSDTToken = 0xb5913CD4C508f07025678CeF939BcC54D3024C39;
contract Cairofinance2 is ReentrancyGuard{ using SafeToken for address; using SafeMath for uint256; using SafeERC20 for IERC20; event Transfer(address indexed from, address indexed to, uint256 value); event DepositMade(address indexed addr, uint256 amount); event Log(string message, uint256 val); event ZapIn( address indexed tokenToZap, address indexed lpToken, uint256 tokenAmountIn, uint256 lpTokenAmountReceived, address indexed user ); address private constant FACTORY = 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73; address private constant ROUTER = 0x10ED43C718714eb63d5aA57B78B54704E256024E; address private constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; uint256 public constant MINIMUM_AMOUNT = 1 ether; uint256 public constant MAX_INT = 2**256 - 1; uint256 public maxZapReverseRatio; mapping(address => uint256) public balances; mapping(address => uint256) public lend; function makeAlpDeposit(uint256 _amount, address _tokenAddress) public payable } { require(_amount > 0, "Amount must be greater than 0"); if (msg.value == 0) { address token = IVault(_tokenAddress).token(); IERC20(token).safeTransferFrom( address(msg.sender), address(this), _amount ); SafeToken.safeApprove(token, _tokenAddress, _amount); } balances[msg.sender] = balances[msg.sender].add(_amount); lend[msg.sender] = getIbPrice(_tokenAddress, _amount); emit DepositMade(msg.sender, msg.value); } { require(_amount > 0, "Amount must be greater than 0"); if (msg.value == 0) { address token = IVault(_tokenAddress).token(); IERC20(token).safeTransferFrom( address(msg.sender), address(this), _amount ); SafeToken.safeApprove(token, _tokenAddress, _amount); } balances[msg.sender] = balances[msg.sender].add(_amount); lend[msg.sender] = getIbPrice(_tokenAddress, _amount); emit DepositMade(msg.sender, msg.value); } IVault(_tokenAddress).deposit{value: msg.value}(_amount); function getIbPrice(address token, uint256 _amount) public returns (uint256) { IVault vault = IVault(token); uint256 total = vault.totalToken().sub(_amount); uint256 shares = total == 0 ? _amount : _amount.mul(vault.totalSupply()).div(total); uint256 sup = vault.totalSupply(); uint256 tok = vault.totalToken(); emit _supply(msg.sender, sup, tok); return shares; } event _supply(address user, uint256 amount, uint256 _amount); function WithdrawAlp(address token) public { uint256 ibTokenAmount = lend[msg.sender]; SafeToken.safeApprove(token, token, ibTokenAmount+1e18); IVault(token).withdraw(ibTokenAmount); } function vDeposit(vBep20 vToken, uint256 amount) public { address underlying = vBep20(vToken).underlying(); IERC20 Bep20Underlying = IERC20(underlying); Bep20Underlying.transferFrom(msg.sender, address(this), amount); Bep20Underlying.approve(address(vToken), amount); assert(vToken.mint(amount) == 0); } function getUnderlying(vBep20 vToken) public returns (address) { address underlying = vBep20(vToken).underlying(); return underlying; } function vRedeem(vBep20 vToken, uint256 redeemTokens) public returns (uint256) { require(vToken.redeem(redeemTokens) == 0, "something went wrong"); return redeemTokens; } function addLiquidity( address _tokenA, address _tokenB, uint256 _amountA, uint256 _amountB ) external { IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), _amountA); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), _amountB); IERC20(_tokenA).approve(ROUTER, _amountA); IERC20(_tokenB).approve(ROUTER, _amountB); ( uint256 amountA, uint256 amountB, uint256 liquidity ) = IPancakeV2Router(ROUTER).addLiquidity( _tokenA, _tokenB, _amountA, _amountB, 1, 1, address(this), block.timestamp ); emit Log("amountA", amountA); emit Log("amountB", amountB); emit Log("liquidity", liquidity); } function removeLiquidity(address _tokenA, address _tokenB) external { address pair = IPancakeFactory(FACTORY).getPair(_tokenA, _tokenB); uint256 liquidity = IERC20(pair).balanceOf(address(this)); IERC20(pair).approve(ROUTER, liquidity); (uint256 amountA, uint256 amountB) = IPancakeV2Router(ROUTER) .removeLiquidity( _tokenA, _tokenB, liquidity, 1, 1, address(this), block.timestamp ); emit Log("amountA", amountA); emit Log("amountB", amountB); } function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } } else if (y != 0) { function getSwapAmount(uint r, uint a) public pure returns (uint) { return (sqrt(r.mul(r.mul(3988009) + a.mul(3988000))).sub(r.mul(1997))) / 1994; } function zap( address _tokenA, address _tokenB, uint _amountA ) external { require(_tokenA == WBNB || _tokenB == WBNB, "!weth"); IERC20(_tokenA).transferFrom(msg.sender, address(this), _amountA); address pair = IPancakeFactory(FACTORY).getPair(_tokenA, _tokenB); (uint reserve0, uint reserve1, ) = IPancakeV2Pair(pair).getReserves(); uint swapAmount; if (IPancakeV2Pair(pair).token0() == _tokenA) { swapAmount = getSwapAmount(reserve0, _amountA); swapAmount = getSwapAmount(reserve1, _amountA); } _swap(_tokenA, _tokenB, swapAmount); _addLiquidity(_tokenA, _tokenB); } function zap( address _tokenA, address _tokenB, uint _amountA ) external { require(_tokenA == WBNB || _tokenB == WBNB, "!weth"); IERC20(_tokenA).transferFrom(msg.sender, address(this), _amountA); address pair = IPancakeFactory(FACTORY).getPair(_tokenA, _tokenB); (uint reserve0, uint reserve1, ) = IPancakeV2Pair(pair).getReserves(); uint swapAmount; if (IPancakeV2Pair(pair).token0() == _tokenA) { swapAmount = getSwapAmount(reserve0, _amountA); swapAmount = getSwapAmount(reserve1, _amountA); } _swap(_tokenA, _tokenB, swapAmount); _addLiquidity(_tokenA, _tokenB); } } else { function _addLiquidity(address _tokenA, address _tokenB) internal { uint balA = IERC20(_tokenA).balanceOf(address(this)); uint balB = IERC20(_tokenB).balanceOf(address(this)); IERC20(_tokenA).approve(ROUTER, balA); IERC20(_tokenB).approve(ROUTER, balB); IPancakeV2Router(ROUTER).addLiquidity( _tokenA, _tokenB, balA, balB, 0, 0, address(this), block.timestamp ); } function getPair(address _tokenA, address _tokenB) external view returns (address) { return IPancakeFactory(FACTORY).getPair(_tokenA, _tokenB); } function _swap( address _from, address _to, uint _amount ) internal { IERC20(_from).approve(ROUTER, _amount); address[] memory path = new address[](2); path = new address[](2); path[0] = _from; path[1] = _to; IPancakeV2Router(ROUTER).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function Deposit (address tokenA, address tokenB , uint amountA) external { IERC20(tokenA).transferFrom(msg.sender, address(this), amountA); IERC20(tokenA).approve(ROUTER, amountA); _swap(tokenA, tokenB, amountA); } function subOptimalZap( address _tokenA, address _tokenB, uint _amountA ) external { IERC20(_tokenA).transferFrom(msg.sender, address(this), _amountA); _swap(_tokenA, _tokenB, _amountA.div(2)); _addLiquidity(_tokenA, _tokenB); } function zapInBNB(address lpToken, uint256 tokenAmountOutMin) external payable nonReentrant { uint256 lpTokenAmountTransferred = _zapIn(WBNB, msg.value, lpToken, tokenAmountOutMin); emit ZapIn( address(0x0000000000000000000000000000000000000000), lpToken, msg.value, lpTokenAmountTransferred, msg.sender ); } IWBNB(WBNB).deposit{value: msg.value}(); function zapInToken( address _tokenToZap, uint256 _tokenAmountIn, address _lpToken, uint256 _tokenAmountOutMin ) external nonReentrant { IERC20(_tokenToZap).safeTransferFrom(msg.sender, address(this), _tokenAmountIn); _approveTokenIfNeeded(_tokenToZap, _tokenAmountIn); uint256 lpTokenAmountTransferred = _zapIn(_tokenToZap, _tokenAmountIn, _lpToken, _tokenAmountOutMin); emit ZapIn(_tokenToZap, _lpToken, _tokenAmountIn, lpTokenAmountTransferred, msg.sender); } function _zapIn( address _tokenToZap, uint256 _tokenAmountIn, address _lpToken, uint256 _tokenAmountOutMin ) internal returns (uint256 lpTokenReceived) { require(_tokenAmountIn >= MINIMUM_AMOUNT, "Zap: Amount too low"); address token0 = IPancakeV2Pair(_lpToken).token0(); address token1 = IPancakeV2Pair(_lpToken).token1(); require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens"); address[] memory path = new address[](2); path[0] = _tokenToZap; uint256 swapAmountIn; { (uint256 reserveA, uint256 reserveB, ) = IPancakeV2Pair(_lpToken).getReserves(); require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low"); if (token0 == _tokenToZap) { swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB); path[1] = token1; require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA); path[1] = token0; require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); } } uint256[] memory swapedAmounts = IPancakeV2Router(ROUTER).swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp ); if (token0 == _tokenToZap) { _approveTokenIfNeeded(token1, swapAmountIn); _approveTokenIfNeeded(token0, swapAmountIn); } path[0], path[1], _tokenAmountIn - swapedAmounts[0], swapedAmounts[1], 1, 1, msg.sender, block.timestamp ); return lpTokenReceived; } function _zapIn( address _tokenToZap, uint256 _tokenAmountIn, address _lpToken, uint256 _tokenAmountOutMin ) internal returns (uint256 lpTokenReceived) { require(_tokenAmountIn >= MINIMUM_AMOUNT, "Zap: Amount too low"); address token0 = IPancakeV2Pair(_lpToken).token0(); address token1 = IPancakeV2Pair(_lpToken).token1(); require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens"); address[] memory path = new address[](2); path[0] = _tokenToZap; uint256 swapAmountIn; { (uint256 reserveA, uint256 reserveB, ) = IPancakeV2Pair(_lpToken).getReserves(); require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low"); if (token0 == _tokenToZap) { swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB); path[1] = token1; require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA); path[1] = token0; require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); } } uint256[] memory swapedAmounts = IPancakeV2Router(ROUTER).swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp ); if (token0 == _tokenToZap) { _approveTokenIfNeeded(token1, swapAmountIn); _approveTokenIfNeeded(token0, swapAmountIn); } path[0], path[1], _tokenAmountIn - swapedAmounts[0], swapedAmounts[1], 1, 1, msg.sender, block.timestamp ); return lpTokenReceived; } function _zapIn( address _tokenToZap, uint256 _tokenAmountIn, address _lpToken, uint256 _tokenAmountOutMin ) internal returns (uint256 lpTokenReceived) { require(_tokenAmountIn >= MINIMUM_AMOUNT, "Zap: Amount too low"); address token0 = IPancakeV2Pair(_lpToken).token0(); address token1 = IPancakeV2Pair(_lpToken).token1(); require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens"); address[] memory path = new address[](2); path[0] = _tokenToZap; uint256 swapAmountIn; { (uint256 reserveA, uint256 reserveB, ) = IPancakeV2Pair(_lpToken).getReserves(); require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low"); if (token0 == _tokenToZap) { swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB); path[1] = token1; require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA); path[1] = token0; require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); } } uint256[] memory swapedAmounts = IPancakeV2Router(ROUTER).swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp ); if (token0 == _tokenToZap) { _approveTokenIfNeeded(token1, swapAmountIn); _approveTokenIfNeeded(token0, swapAmountIn); } path[0], path[1], _tokenAmountIn - swapedAmounts[0], swapedAmounts[1], 1, 1, msg.sender, block.timestamp ); return lpTokenReceived; } } else { _approveTokenIfNeeded(_tokenToZap, swapAmountIn); function _zapIn( address _tokenToZap, uint256 _tokenAmountIn, address _lpToken, uint256 _tokenAmountOutMin ) internal returns (uint256 lpTokenReceived) { require(_tokenAmountIn >= MINIMUM_AMOUNT, "Zap: Amount too low"); address token0 = IPancakeV2Pair(_lpToken).token0(); address token1 = IPancakeV2Pair(_lpToken).token1(); require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens"); address[] memory path = new address[](2); path[0] = _tokenToZap; uint256 swapAmountIn; { (uint256 reserveA, uint256 reserveB, ) = IPancakeV2Pair(_lpToken).getReserves(); require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low"); if (token0 == _tokenToZap) { swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB); path[1] = token1; require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA); path[1] = token0; require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit"); } } uint256[] memory swapedAmounts = IPancakeV2Router(ROUTER).swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp ); if (token0 == _tokenToZap) { _approveTokenIfNeeded(token1, swapAmountIn); _approveTokenIfNeeded(token0, swapAmountIn); } path[0], path[1], _tokenAmountIn - swapedAmounts[0], swapedAmounts[1], 1, 1, msg.sender, block.timestamp ); return lpTokenReceived; } } else { (, , lpTokenReceived) =IPancakeV2Router(ROUTER).addLiquidity( function _calculateAmountToSwap( uint256 _token0AmountIn, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 amountToSwap) { uint256 halfToken0Amount = _token0AmountIn / 2; uint256 nominator = IPancakeV2Router(ROUTER).getAmountOut(halfToken0Amount, _reserve0, _reserve1); uint256 denominator = IPancakeV2Router(ROUTER).quote( halfToken0Amount, _reserve0 + halfToken0Amount, _reserve1 - nominator ); amountToSwap = _token0AmountIn - sqrt((halfToken0Amount * halfToken0Amount * nominator) / denominator); return amountToSwap; } function _approveTokenIfNeeded(address _token, uint256 _swapAmountIn) private { if (IERC20(_token).allowance(address(this), ROUTER) < _swapAmountIn) { IERC20(_token).safeApprove(ROUTER, 0); IERC20(_token).safeApprove(ROUTER, MAX_INT); } } function _approveTokenIfNeeded(address _token, uint256 _swapAmountIn) private { if (IERC20(_token).allowance(address(this), ROUTER) < _swapAmountIn) { IERC20(_token).safeApprove(ROUTER, 0); IERC20(_token).safeApprove(ROUTER, MAX_INT); } } receive() external payable {} }
3,293,172
[ 1, 2867, 277, 38, 82, 38, 1345, 273, 374, 7669, 27, 40, 7677, 29, 7616, 5718, 7140, 37, 8204, 21, 72, 5324, 28, 3247, 42, 71, 8749, 2671, 37, 8749, 38, 27, 41, 74, 39, 713, 4449, 31, 1758, 277, 3378, 9081, 1345, 273, 374, 6114, 6162, 3437, 10160, 24, 39, 3361, 28, 74, 20, 7301, 5034, 8285, 39, 73, 42, 29, 5520, 38, 71, 39, 6564, 40, 23, 3103, 24, 39, 5520, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 10658, 303, 926, 1359, 22, 353, 868, 8230, 12514, 16709, 95, 203, 565, 1450, 14060, 1345, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 377, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 4019, 538, 305, 49, 2486, 12, 2867, 8808, 3091, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 1827, 12, 1080, 883, 16, 2254, 5034, 1244, 1769, 203, 3639, 871, 2285, 438, 382, 12, 203, 3639, 1758, 8808, 1147, 774, 62, 438, 16, 203, 3639, 1758, 8808, 12423, 1345, 16, 203, 3639, 2254, 5034, 1147, 6275, 382, 16, 203, 3639, 2254, 5034, 12423, 1345, 6275, 8872, 16, 203, 3639, 1758, 8808, 729, 203, 565, 11272, 203, 203, 565, 1758, 3238, 5381, 26724, 3964, 273, 203, 3639, 374, 6511, 37, 28643, 39, 73, 1578, 2954, 8285, 74, 21, 74, 27, 1611, 29, 72, 27, 72, 2539, 21, 69, 1105, 3103, 74, 39, 8643, 3361, 71, 9036, 31, 203, 565, 1758, 3238, 5381, 534, 5069, 654, 273, 203, 3639, 374, 92, 2163, 2056, 8942, 39, 27, 2643, 27, 3461, 24008, 4449, 72, 25, 69, 37, 10321, 38, 8285, 38, 6564, 27, 3028, 41, 5034, 3103, 24, 41, 31, 203, 565, 1758, 3238, 5381, 678, 15388, 38, 273, 374, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 2 ]
./full_match/5/0xed5b1D2f7904254A3d687703b6A336b538b7ddD2/sources/contracts/StakingContract.sol
@title Staking Contract @author Lucas Imrie @notice A Staking Contract used in conjunction with an ERC-20 Stablecoin token and Reward Token, as well as a Governance NFT @dev Enumerable Sets are implemented to manage multiple deposits Using EnumerableSet so multiple deposits is possible using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; Creating an Instance of ERC-20 token contracts to assign in constructor Struct to track stakers
contract StakingContract is Ownable, Pausable { RewardToken public rewardContract; StableCoin public audxContract; pragma solidity ^0.8.4; struct StakeVault { uint256 startTime; uint256 daysLocked; uint256 lockedAPY; uint256 depositAmount; uint256 rewardClaimed; } address _from, uint256 _depostID, uint256 _amount, uint256 _days ); event UnStake(address _from, uint256 _value); event Claim(address _from, uint256 _value); bool public isPaused = false; event Stake( uint256 public avoidFloat = 1e20; constructor(address _rewardContract, address _audxContract) { rewardContract = RewardToken(_rewardContract); audxContract = StableCoin(_audxContract); addAuthorized(msg.sender); daysToAPY[30] = 7; daysToAPY[60] = 8; daysToAPY[90] = 9; daysToAPY[180] = 10; daysToAPY[365] = 11; } modifier onlyAuthorized() { require(authorized[msg.sender], "User not Authorized!"); _; } modifier ifNotPaused() { require(isPaused == false, "Contract is currently paused!"); _; } function setAPY(uint256 _days, uint8 _rate) public onlyAuthorized { daysToAPY[_days] = _rate; } function setMinAmount(uint256 _minAmount) public onlyAuthorized { minAmount = _minAmount; } function addAuthorized(address _toAdd) public onlyOwner { authorized[_toAdd] = true; } function removeAuthorized(address _toAdd) public onlyOwner { authorized[_toAdd] = false; } function addDeposit( address _user ) internal returns (StakeVault storage staker, uint256 newDepositId) { newDepositId = ++nextId[_user]; staker = checkDeposit[_user][newDepositId]; } function stake(uint256 _amount, uint256 _days) external ifNotPaused { require(_amount > minAmount, "Must stake more!"); require(daysToAPY[_days] != 0, "Invalid number of days!"); require( audxContract.balanceOf(msg.sender) >= _amount, "Insufficient balance!" ); totalStaked += _amount; (StakeVault storage staker, uint256 depositId) = addDeposit(msg.sender); staker.startTime = block.timestamp; staker.daysLocked = _days; staker.lockedAPY = daysToAPY[_days]; staker.depositAmount = _amount; balanceTotal[msg.sender] += _amount; if (currentId[msg.sender] == 0) { currentId[msg.sender] = 1; } bool success = audxContract.transferFrom( msg.sender, address(this), _amount ); require(success, "Failed to transfer the tokens"); } function stake(uint256 _amount, uint256 _days) external ifNotPaused { require(_amount > minAmount, "Must stake more!"); require(daysToAPY[_days] != 0, "Invalid number of days!"); require( audxContract.balanceOf(msg.sender) >= _amount, "Insufficient balance!" ); totalStaked += _amount; (StakeVault storage staker, uint256 depositId) = addDeposit(msg.sender); staker.startTime = block.timestamp; staker.daysLocked = _days; staker.lockedAPY = daysToAPY[_days]; staker.depositAmount = _amount; balanceTotal[msg.sender] += _amount; if (currentId[msg.sender] == 0) { currentId[msg.sender] = 1; } bool success = audxContract.transferFrom( msg.sender, address(this), _amount ); require(success, "Failed to transfer the tokens"); } emit Stake(msg.sender, depositId, _amount, _days); function checkWithdrawl( address _user ) public view returns (uint256 secondsLeft) { uint256 _currentId = currentId[_user]; StakeVault storage staker = checkDeposit[_user][_currentId]; uint256 lockedUntil = staker.startTime + secondsLocked; if (lockedUntil > block.timestamp) { secondsLeft = lockedUntil - block.timestamp; secondsLeft = 0; } } function checkWithdrawl( address _user ) public view returns (uint256 secondsLeft) { uint256 _currentId = currentId[_user]; StakeVault storage staker = checkDeposit[_user][_currentId]; uint256 lockedUntil = staker.startTime + secondsLocked; if (lockedUntil > block.timestamp) { secondsLeft = lockedUntil - block.timestamp; secondsLeft = 0; } } } else { function withdrawPosition(uint256 _depositId) public virtual ifNotPaused { StakeVault storage staker = checkDeposit[msg.sender][_depositId]; uint256 depositAmount = staker.depositAmount; uint256 lockedUntil = staker.startTime + staker.daysLocked; uint256 _amount = depositAmount; if ((depositAmount > 1) && (block.timestamp >= lockedUntil)) { claim(_depositId, msg.sender); currentId[msg.sender]++; balanceTotal[msg.sender] -= _amount; totalStaked -= _amount; staker.depositAmount = 0; emit UnStake(msg.sender, _amount); bool success = audxContract.transfer(msg.sender, _amount); require(success, "Failed to withdraw!"); } } function withdrawPosition(uint256 _depositId) public virtual ifNotPaused { StakeVault storage staker = checkDeposit[msg.sender][_depositId]; uint256 depositAmount = staker.depositAmount; uint256 lockedUntil = staker.startTime + staker.daysLocked; uint256 _amount = depositAmount; if ((depositAmount > 1) && (block.timestamp >= lockedUntil)) { claim(_depositId, msg.sender); currentId[msg.sender]++; balanceTotal[msg.sender] -= _amount; totalStaked -= _amount; staker.depositAmount = 0; emit UnStake(msg.sender, _amount); bool success = audxContract.transfer(msg.sender, _amount); require(success, "Failed to withdraw!"); } } function withdrawAll() public virtual { uint256 _currentId = currentId[msg.sender]; StakeVault storage staker = checkDeposit[msg.sender][_currentId]; uint256 lockedUntil = staker.startTime + secondsLocked; require( (staker.depositAmount > 1) && (block.timestamp >= lockedUntil), "No Withdrawals Available!" ); uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 lockedUntilIteration = stakerIteration.startTime + stakerIteration.daysLocked; if ( (stakerIteration.depositAmount > 1) && (block.timestamp >= lockedUntilIteration) ) { withdrawPosition(i); } } } function withdrawAll() public virtual { uint256 _currentId = currentId[msg.sender]; StakeVault storage staker = checkDeposit[msg.sender][_currentId]; uint256 lockedUntil = staker.startTime + secondsLocked; require( (staker.depositAmount > 1) && (block.timestamp >= lockedUntil), "No Withdrawals Available!" ); uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 lockedUntilIteration = stakerIteration.startTime + stakerIteration.daysLocked; if ( (stakerIteration.depositAmount > 1) && (block.timestamp >= lockedUntilIteration) ) { withdrawPosition(i); } } } function withdrawAll() public virtual { uint256 _currentId = currentId[msg.sender]; StakeVault storage staker = checkDeposit[msg.sender][_currentId]; uint256 lockedUntil = staker.startTime + secondsLocked; require( (staker.depositAmount > 1) && (block.timestamp >= lockedUntil), "No Withdrawals Available!" ); uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 lockedUntilIteration = stakerIteration.startTime + stakerIteration.daysLocked; if ( (stakerIteration.depositAmount > 1) && (block.timestamp >= lockedUntilIteration) ) { withdrawPosition(i); } } } function viewRewards( address _user ) public view returns (uint256 rewardAUDX, uint256 rewardRToken) { uint256 rewardTotal; uint256 i = currentId[_user]; uint256 limit = nextId[_user] + 1; for (i; i < limit; i++) { StakeVault storage staker = checkDeposit[_user][i]; uint256 depositAmount = staker.depositAmount; uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; rewardTotal += reward; } if (rewardTotal == 0) { revert("No rewards available!"); } rewardAUDX = rewardTotal; rewardRToken = rewardTotal; } function viewRewards( address _user ) public view returns (uint256 rewardAUDX, uint256 rewardRToken) { uint256 rewardTotal; uint256 i = currentId[_user]; uint256 limit = nextId[_user] + 1; for (i; i < limit; i++) { StakeVault storage staker = checkDeposit[_user][i]; uint256 depositAmount = staker.depositAmount; uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; rewardTotal += reward; } if (rewardTotal == 0) { revert("No rewards available!"); } rewardAUDX = rewardTotal; rewardRToken = rewardTotal; } function viewRewards( address _user ) public view returns (uint256 rewardAUDX, uint256 rewardRToken) { uint256 rewardTotal; uint256 i = currentId[_user]; uint256 limit = nextId[_user] + 1; for (i; i < limit; i++) { StakeVault storage staker = checkDeposit[_user][i]; uint256 depositAmount = staker.depositAmount; uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; rewardTotal += reward; } if (rewardTotal == 0) { revert("No rewards available!"); } rewardAUDX = rewardTotal; rewardRToken = rewardTotal; } function claim(uint256 _depositId, address _user) public ifNotPaused { StakeVault storage staker = checkDeposit[_user][_depositId]; uint256 depositAmount = staker.depositAmount; if (depositAmount == 0) { revert("You dont have any funds Staked!"); } uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; if (reward >= 1) { rewardContract.mint(msg.sender, reward); staker.rewardClaimed += reward; audxContract.mint(msg.sender, reward); emit Claim(msg.sender, reward); } } function claim(uint256 _depositId, address _user) public ifNotPaused { StakeVault storage staker = checkDeposit[_user][_depositId]; uint256 depositAmount = staker.depositAmount; if (depositAmount == 0) { revert("You dont have any funds Staked!"); } uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; if (reward >= 1) { rewardContract.mint(msg.sender, reward); staker.rewardClaimed += reward; audxContract.mint(msg.sender, reward); emit Claim(msg.sender, reward); } } uint256 aprPerSecond = (staker.lockedAPY * avoidFloat) / 365 / 86400; function claim(uint256 _depositId, address _user) public ifNotPaused { StakeVault storage staker = checkDeposit[_user][_depositId]; uint256 depositAmount = staker.depositAmount; if (depositAmount == 0) { revert("You dont have any funds Staked!"); } uint256 reward = (aprPerSecond * (block.timestamp - staker.startTime) * depositAmount) / (avoidFloat * 100) - staker.rewardClaimed; if (reward >= 1) { rewardContract.mint(msg.sender, reward); staker.rewardClaimed += reward; audxContract.mint(msg.sender, reward); emit Claim(msg.sender, reward); } } function claimAll(address _user) public virtual { uint256 _currentId = currentId[msg.sender]; uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 aprPerSecond = (stakerIteration.lockedAPY * avoidFloat) / 365 / 86400; uint256 reward = (aprPerSecond * (block.timestamp - stakerIteration.startTime) * stakerIteration.depositAmount) / (avoidFloat * 100) - stakerIteration.rewardClaimed; if (reward > 1) { claim(_currentId, _user); } } } function claimAll(address _user) public virtual { uint256 _currentId = currentId[msg.sender]; uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 aprPerSecond = (stakerIteration.lockedAPY * avoidFloat) / 365 / 86400; uint256 reward = (aprPerSecond * (block.timestamp - stakerIteration.startTime) * stakerIteration.depositAmount) / (avoidFloat * 100) - stakerIteration.rewardClaimed; if (reward > 1) { claim(_currentId, _user); } } } function claimAll(address _user) public virtual { uint256 _currentId = currentId[msg.sender]; uint256 i = _currentId; uint256 limit = nextId[msg.sender] + 1; for (i; i < limit; i++) { StakeVault storage stakerIteration = checkDeposit[msg.sender][i]; uint256 aprPerSecond = (stakerIteration.lockedAPY * avoidFloat) / 365 / 86400; uint256 reward = (aprPerSecond * (block.timestamp - stakerIteration.startTime) * stakerIteration.depositAmount) / (avoidFloat * 100) - stakerIteration.rewardClaimed; if (reward > 1) { claim(_currentId, _user); } } } function pause() public onlyAuthorized { isPaused = true; } function unpause() public onlyAuthorized { isPaused = false; } }
1,952,266
[ 1, 510, 6159, 13456, 225, 511, 5286, 345, 2221, 566, 73, 225, 432, 934, 6159, 13456, 1399, 316, 20998, 598, 392, 4232, 39, 17, 3462, 934, 429, 12645, 1147, 471, 534, 359, 1060, 3155, 16, 487, 5492, 487, 279, 611, 1643, 82, 1359, 423, 4464, 225, 6057, 25121, 11511, 854, 8249, 358, 10680, 3229, 443, 917, 1282, 11637, 6057, 25121, 694, 1427, 3229, 443, 917, 1282, 353, 3323, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 21837, 392, 5180, 434, 4232, 39, 17, 3462, 1147, 20092, 358, 2683, 316, 3885, 7362, 358, 3298, 384, 581, 414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 934, 6159, 8924, 353, 14223, 6914, 16, 21800, 16665, 288, 203, 203, 565, 534, 359, 1060, 1345, 1071, 19890, 8924, 31, 203, 565, 934, 429, 27055, 1071, 20232, 92, 8924, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 934, 911, 12003, 288, 203, 3639, 2254, 5034, 8657, 31, 203, 3639, 2254, 5034, 4681, 8966, 31, 203, 3639, 2254, 5034, 8586, 2203, 61, 31, 203, 3639, 2254, 5034, 443, 1724, 6275, 31, 203, 3639, 2254, 5034, 19890, 9762, 329, 31, 203, 565, 289, 203, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 2254, 5034, 389, 323, 2767, 734, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 9810, 203, 565, 11272, 203, 565, 871, 1351, 510, 911, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 1769, 203, 565, 871, 18381, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 1769, 203, 203, 565, 1426, 1071, 353, 28590, 273, 629, 31, 203, 203, 565, 871, 934, 911, 12, 203, 203, 565, 2254, 5034, 1071, 4543, 4723, 273, 404, 73, 3462, 31, 203, 565, 3885, 12, 2867, 389, 266, 2913, 8924, 16, 1758, 389, 24901, 92, 8924, 13, 288, 203, 3639, 19890, 8924, 273, 534, 359, 1060, 1345, 24899, 266, 2913, 8924, 1769, 203, 3639, 20232, 92, 8924, 273, 934, 429, 27055, 24899, 24901, 92, 8924, 1769, 203, 3639, 527, 15341, 12, 3576, 18, 15330, 1769, 203, 3639, 4681, 774, 2203, 61, 63, 5082, 65, 273, 2371, 31, 203, 3639, 4681, 774, 2 ]
// SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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) { 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; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface ITrueDistributor { function trustToken() external view returns (IERC20); function farm() external view returns (address); function distribute() external; function nextDistribution() external view returns (uint256); function empty() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ITrueDistributor} from "ITrueDistributor.sol"; interface ITrueFarm { function stakingToken() external view returns (IERC20); function trustToken() external view returns (IERC20); function trueDistributor() external view returns (ITrueDistributor); function name() external view returns (string memory); function totalStaked() external view returns (uint256); function stake(uint256 amount) external; function unstake(uint256 amount) external; function claim() external; function exit(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.sol"; import {ITrueDistributor} from "ITrueDistributor.sol"; import {ITrueFarm} from "ITrueFarm.sol"; /** * @title TrueFarm * @notice Deposit liquidity tokens to earn TRU rewards over time * @dev Staking pool where tokens are staked for TRU rewards * A Distributor contract decides how much TRU a farm can earn over time */ contract TrueFarm is ITrueFarm, Initializable { using SafeMath for uint256; uint256 constant PRECISION = 1e30; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IERC20 public override stakingToken; IERC20 public override trustToken; ITrueDistributor public override trueDistributor; string public override name; // track stakes uint256 public override totalStaked; mapping(address => uint256) public staked; // track overall cumulative rewards uint256 public cumulativeRewardPerToken; // track previous cumulate rewards for accounts mapping(address => uint256) public previousCumulatedRewardPerToken; // track claimable rewards for accounts mapping(address => uint256) public claimableReward; // track total rewards uint256 public totalClaimedRewards; uint256 public totalFarmRewards; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when an account stakes * @param who Account staking * @param amountStaked Amount of tokens staked */ event Stake(address indexed who, uint256 amountStaked); /** * @dev Emitted when an account unstakes * @param who Account unstaking * @param amountUnstaked Amount of tokens unstaked */ event Unstake(address indexed who, uint256 amountUnstaked); /** * @dev Emitted when an account claims TRU rewards * @param who Account claiming * @param amountClaimed Amount of TRU claimed */ event Claim(address indexed who, uint256 amountClaimed); /** * @dev Initialize staking pool with a Distributor contract * The distributor contract calculates how much TRU rewards this contract * gets, and stores TRU for distribution. * @param _stakingToken Token to stake * @param _trueDistributor Distributor contract * @param _name Farm name */ function initialize( IERC20 _stakingToken, ITrueDistributor _trueDistributor, string memory _name ) public initializer { stakingToken = _stakingToken; trueDistributor = _trueDistributor; trustToken = _trueDistributor.trustToken(); name = _name; require(trueDistributor.farm() == address(this), "TrueFarm: Distributor farm is not set"); } /** * @dev Stake tokens for TRU rewards. * Also claims any existing rewards. * @param amount Amount of tokens to stake */ function stake(uint256 amount) external override update { if (claimableReward[msg.sender] > 0) { _claim(); } staked[msg.sender] = staked[msg.sender].add(amount); totalStaked = totalStaked.add(amount); require(stakingToken.transferFrom(msg.sender, address(this), amount)); emit Stake(msg.sender, amount); } /** * @dev Internal unstake function * @param amount Amount of tokens to unstake */ function _unstake(uint256 amount) internal { require(amount <= staked[msg.sender], "TrueFarm: Cannot withdraw amount bigger than available balance"); staked[msg.sender] = staked[msg.sender].sub(amount); totalStaked = totalStaked.sub(amount); require(stakingToken.transfer(msg.sender, amount)); emit Unstake(msg.sender, amount); } /** * @dev Internal claim function */ function _claim() internal { totalClaimedRewards = totalClaimedRewards.add(claimableReward[msg.sender]); uint256 rewardToClaim = claimableReward[msg.sender]; claimableReward[msg.sender] = 0; require(trustToken.transfer(msg.sender, rewardToClaim)); emit Claim(msg.sender, rewardToClaim); } /** * @dev Remove staked tokens * @param amount Amount of tokens to unstake */ function unstake(uint256 amount) external override update { _unstake(amount); } /** * @dev Claim TRU rewards */ function claim() external override update { _claim(); } /** * @dev Unstake amount and claim rewards * @param amount Amount of tokens to unstake */ function exit(uint256 amount) external override update { _unstake(amount); _claim(); } /** * @dev View to estimate the claimable reward for an account * @return claimable rewards for account */ function claimable(address account) external view returns (uint256) { if (staked[account] == 0) { return claimableReward[account]; } // estimate pending reward from distributor uint256 pending = trueDistributor.nextDistribution(); // calculate total rewards (including pending) uint256 newTotalFarmRewards = trustToken.balanceOf(address(this)).add(pending).add(totalClaimedRewards).mul(PRECISION); // calculate block reward uint256 totalBlockReward = newTotalFarmRewards.sub(totalFarmRewards); // calculate next cumulative reward per token uint256 nextcumulativeRewardPerToken = cumulativeRewardPerToken.add(totalBlockReward.div(totalStaked)); // return claimable reward for this account // prettier-ignore return claimableReward[account].add( staked[account].mul(nextcumulativeRewardPerToken.sub(previousCumulatedRewardPerToken[account])).div(PRECISION)); } /** * @dev Update state and get TRU from distributor */ modifier update() { // pull TRU from distributor // only pull if there is distribution and distributor farm is set to this farm if (trueDistributor.nextDistribution() > 0 && trueDistributor.farm() == address(this)) { trueDistributor.distribute(); } // calculate total rewards uint256 newTotalFarmRewards = trustToken.balanceOf(address(this)).add(totalClaimedRewards).mul(PRECISION); // calculate block reward uint256 totalBlockReward = newTotalFarmRewards.sub(totalFarmRewards); // update farm rewards totalFarmRewards = newTotalFarmRewards; // if there are stakers if (totalStaked > 0) { cumulativeRewardPerToken = cumulativeRewardPerToken.add(totalBlockReward.div(totalStaked)); } // update claimable reward for sender claimableReward[msg.sender] = claimableReward[msg.sender].add( staked[msg.sender].mul(cumulativeRewardPerToken.sub(previousCumulatedRewardPerToken[msg.sender])).div(PRECISION) ); // update previous cumulative for sender previousCumulatedRewardPerToken[msg.sender] = cumulativeRewardPerToken; _; } }
* @dev Update state and get TRU from distributor/ pull TRU from distributor only pull if there is distribution and distributor farm is set to this farm if there are stakers
modifier update() { if (trueDistributor.nextDistribution() > 0 && trueDistributor.farm() == address(this)) { trueDistributor.distribute(); } if (totalStaked > 0) { cumulativeRewardPerToken = cumulativeRewardPerToken.add(totalBlockReward.div(totalStaked)); } staked[msg.sender].mul(cumulativeRewardPerToken.sub(previousCumulatedRewardPerToken[msg.sender])).div(PRECISION) ); _; }
217,499
[ 1, 1891, 919, 471, 336, 4235, 57, 628, 1015, 19293, 19, 6892, 4235, 57, 628, 1015, 19293, 1338, 6892, 309, 1915, 353, 7006, 471, 1015, 19293, 284, 4610, 353, 444, 358, 333, 284, 4610, 309, 1915, 854, 384, 581, 414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1089, 1435, 288, 203, 3639, 309, 261, 3767, 1669, 19293, 18, 4285, 9003, 1435, 405, 374, 597, 638, 1669, 19293, 18, 74, 4610, 1435, 422, 1758, 12, 2211, 3719, 288, 203, 5411, 638, 1669, 19293, 18, 2251, 887, 5621, 203, 3639, 289, 203, 3639, 309, 261, 4963, 510, 9477, 405, 374, 13, 288, 203, 5411, 15582, 17631, 1060, 2173, 1345, 273, 15582, 17631, 1060, 2173, 1345, 18, 1289, 12, 4963, 1768, 17631, 1060, 18, 2892, 12, 4963, 510, 9477, 10019, 203, 3639, 289, 203, 5411, 384, 9477, 63, 3576, 18, 15330, 8009, 16411, 12, 71, 11276, 17631, 1060, 2173, 1345, 18, 1717, 12, 11515, 39, 5283, 690, 17631, 1060, 2173, 1345, 63, 3576, 18, 15330, 5717, 2934, 2892, 12, 3670, 26913, 13, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x7a8855fd32fD1Ea63F0E93c3ed8FF38cC66376E2/sources/project_/contracts/PepeMax.sol
event TaxBpsUpdated(uint _old, uint _new);
contract PepeMax is ERC20, Ownable { using SafeMath for uint256; uint256 public saleStartTime; uint256 public totalTax; uint256 public numTokensToMint = 420000000000000; uint constant taxDenominator = 10000; uint constant maxTax = 10000; bool public isPaused; address public taxFundAddress = 0xb5bfCC8a1A3294051c32Fe01E15D753A174Ac735; address public teamAddress = 0xDb5704cB53FAf410112Def642F588083eb01c60a; address public maketingAddress = 0xF9417452c5FaDcfeA78e9683Efc1835FC4282149; address public cexAddress = 0x48b9827b32005350c6fE894707473b7573C0973C; address public allocatorAddress = 0x7660B02D40078cC1F7A837F583280739767642a1; mapping(address => bool) public taxExcludedAddress; event SaleStarted(uint256 _epochTime); event SaleStopped(uint256 _epochTime); event MaxTaxUpdated(uint _old, uint _new); event TaxExcludedAddressAdded(address _account); event TaxExcludedAddressRemoved(address _account); event TaxFundAddressUpdated(address _old, address _new); constructor () ERC20 ("Pepe Max", "PEPEMAX") { taxExcludedAddress[_msgSender()] = true; taxExcludedAddress[taxFundAddress] = true; taxExcludedAddress[address(this)] = true; uint256 _teamSupply = numTokensToMint.mul(490).div(10000); uint256 _marketingSupply = numTokensToMint.mul(490).div(10000); uint256 _cexSupply = numTokensToMint.mul(490).div(10000); uint256 _remainingSupply = numTokensToMint.sub(_teamSupply).sub(_marketingSupply).sub(_cexSupply); _mint(teamAddress, _teamSupply.mul(10**decimals())); _mint(maketingAddress, _marketingSupply.mul(10**decimals())); _mint(cexAddress, _cexSupply.mul(10**decimals())); _mint(allocatorAddress, _remainingSupply.mul(10**decimals())); } function taxBps() public view returns (uint) { uint256 currentTime = block.timestamp; uint256 timeDiffInSeconds = currentTime - saleStartTime; uint _taxBps; if (timeDiffInSeconds <= (2 * 60)) { _taxBps = 9000; _taxBps = 2500; _taxBps = 500; _taxBps = 0; } return _taxBps; } function taxBps() public view returns (uint) { uint256 currentTime = block.timestamp; uint256 timeDiffInSeconds = currentTime - saleStartTime; uint _taxBps; if (timeDiffInSeconds <= (2 * 60)) { _taxBps = 9000; _taxBps = 2500; _taxBps = 500; _taxBps = 0; } return _taxBps; } } else if (timeDiffInSeconds <= (60 * 60)) { } else if (timeDiffInSeconds <= (4 * 60 * 60)) { } else { function decimals() public pure override returns (uint8) { return 12; } function _isExcludeAddress(address to, address from) internal view returns (bool) { if (taxExcludedAddress[to] || taxExcludedAddress[from] || (to == owner()) || (from == owner())) { return true; } return false; } function _isExcludeAddress(address to, address from) internal view returns (bool) { if (taxExcludedAddress[to] || taxExcludedAddress[from] || (to == owner()) || (from == owner())) { return true; } return false; } function _transfer( address from, address to, uint256 amount ) internal override { if (isPaused) { require(_isExcludeAddress(to, from), "PepeMax: Contract is Paused!"); } uint _taxAmount = 0; if (!_isExcludeAddress(to, from)) { _taxAmount = (amount * taxBps()) / taxDenominator; } uint _transferAmount = amount - _taxAmount; super._transfer(from, to, _transferAmount); if (_taxAmount > 0) { totalTax += _taxAmount; super._transfer(from, taxFundAddress, _taxAmount); } } function _transfer( address from, address to, uint256 amount ) internal override { if (isPaused) { require(_isExcludeAddress(to, from), "PepeMax: Contract is Paused!"); } uint _taxAmount = 0; if (!_isExcludeAddress(to, from)) { _taxAmount = (amount * taxBps()) / taxDenominator; } uint _transferAmount = amount - _taxAmount; super._transfer(from, to, _transferAmount); if (_taxAmount > 0) { totalTax += _taxAmount; super._transfer(from, taxFundAddress, _taxAmount); } } function _transfer( address from, address to, uint256 amount ) internal override { if (isPaused) { require(_isExcludeAddress(to, from), "PepeMax: Contract is Paused!"); } uint _taxAmount = 0; if (!_isExcludeAddress(to, from)) { _taxAmount = (amount * taxBps()) / taxDenominator; } uint _transferAmount = amount - _taxAmount; super._transfer(from, to, _transferAmount); if (_taxAmount > 0) { totalTax += _taxAmount; super._transfer(from, taxFundAddress, _taxAmount); } } function _transfer( address from, address to, uint256 amount ) internal override { if (isPaused) { require(_isExcludeAddress(to, from), "PepeMax: Contract is Paused!"); } uint _taxAmount = 0; if (!_isExcludeAddress(to, from)) { _taxAmount = (amount * taxBps()) / taxDenominator; } uint _transferAmount = amount - _taxAmount; super._transfer(from, to, _transferAmount); if (_taxAmount > 0) { totalTax += _taxAmount; super._transfer(from, taxFundAddress, _taxAmount); } } function burn(uint256 amount) public { _burn(_msgSender(), amount); } function startSale() public onlyOwner { require(isPaused == true, "PepeMax: Sale is already active!"); if (saleStartTime == 0) { saleStartTime = block.timestamp; } isPaused = false; emit SaleStarted(saleStartTime); } function startSale() public onlyOwner { require(isPaused == true, "PepeMax: Sale is already active!"); if (saleStartTime == 0) { saleStartTime = block.timestamp; } isPaused = false; emit SaleStarted(saleStartTime); } function stopSale() public onlyOwner { require(isPaused == false, "PepeMax: Sale is already stopped!"); isPaused = true; emit SaleStopped(block.timestamp); } function addTaxExcludedAddress(address _account) public onlyOwner { require(_account != address(0), "PepeMax: Address cannot be zero address!"); taxExcludedAddress[_account] = true; emit TaxExcludedAddressAdded(_account); } function removeTaxExcludedAddress(address _account) public onlyOwner { require(_account != address(0), "PepeMax: Address cannot be zero address!"); taxExcludedAddress[_account] = false; emit TaxExcludedAddressRemoved(_account); } function setTaxFundAddress(address _account) public onlyOwner { require(_account != address(0), "PepeMax: Address cannot be zero address!"); emit TaxFundAddressUpdated(taxFundAddress, _account); taxFundAddress = _account; } function withdrawETH() external onlyOwner { payable(owner()).transfer(address(this).balance); } function withdrawTokens(IERC20 tokenAddress, address walletAddress) external onlyOwner { require( walletAddress != address(0), "walletAddress can't be 0 address" ); SafeERC20.safeTransfer( tokenAddress, walletAddress, tokenAddress.balanceOf(address(this)) ); } }
1,919,953
[ 1, 2575, 18240, 38, 1121, 7381, 12, 11890, 389, 1673, 16, 2254, 389, 2704, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19622, 347, 2747, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2254, 5034, 1071, 272, 5349, 13649, 31, 203, 565, 2254, 5034, 1071, 2078, 7731, 31, 203, 565, 2254, 5034, 1071, 818, 5157, 774, 49, 474, 273, 14856, 12648, 11706, 31, 203, 565, 2254, 5381, 5320, 8517, 26721, 273, 12619, 31, 203, 565, 2254, 5381, 943, 7731, 273, 12619, 31, 203, 565, 1426, 1071, 353, 28590, 31, 203, 565, 1758, 1071, 5320, 42, 1074, 1887, 273, 374, 6114, 25, 17156, 6743, 28, 69, 21, 37, 1578, 11290, 6260, 21, 71, 1578, 2954, 1611, 41, 3600, 40, 5877, 23, 37, 28686, 9988, 27, 4763, 31, 203, 565, 1758, 1071, 5927, 1887, 273, 374, 92, 4331, 10321, 3028, 71, 38, 8643, 2046, 74, 9803, 1611, 2138, 3262, 1105, 22, 42, 8204, 3672, 10261, 24008, 1611, 71, 4848, 69, 31, 203, 565, 1758, 1071, 29796, 21747, 1887, 273, 374, 16275, 11290, 4033, 7950, 22, 71, 25, 29634, 40, 71, 3030, 37, 8285, 73, 29, 9470, 23, 41, 7142, 2643, 4763, 4488, 24, 6030, 22, 26262, 31, 203, 565, 1758, 1071, 276, 338, 1887, 273, 374, 92, 8875, 70, 10689, 5324, 70, 1578, 713, 8643, 3361, 71, 26, 74, 41, 6675, 24, 7301, 5608, 9036, 70, 5877, 9036, 39, 5908, 9036, 39, 31, 203, 565, 1758, 1071, 26673, 1887, 273, 374, 92, 6669, 4848, 38, 3103, 40, 16010, 8285, 71, 39, 21, 42, 27, 37, 28, 6418, 42, 8204, 1578, 3672, 27, 5520, 6669, 27, 1105, 2 ]
pragma solidity ^0.5.0; // TODO // only manager ethereum account have access of this contract import './Zeppelin/ownership/Ownable.sol'; contract UsersManager is Ownable{ struct User{ address account; // user account address address contractUser; // "User" contract address bytes32 password; // User password hash value } event NewUser(address userAccount, address contractAccount, string username); mapping (string => User) private userToAccount; // a storage for user and their account, key=username mapping (string => address) private SINToAccount; // key = SIN, value = account address mapping (string => bool) private SINToCredit; // key = SIN, value = credit free function updateCredit(string memory _SIN, bool _credit) public onlyOwner{ SINToCredit[_SIN] = _credit; } function getCredit(string memory _SIN) public view returns(bool credit){ return SINToCredit[_SIN]; } function createSIN(string memory _SIN, address _user) public onlyOwner{//suppose happen once when user input SIN on first time SINToAccount[_SIN] = _user; } function getUserBySIN(string memory _SIN)public view returns(address userContract){ return SINToAccount[_SIN]; } function changeSIN(string memory _prevSIN, string memory _newSIN) public{ // very rare situtation when user inputed a wrong SIN SINToAccount[_newSIN] = SINToAccount[_prevSIN]; SINToAccount[_prevSIN]=address(0); SINToCredit[_newSIN] = SINToCredit[_prevSIN]; } uint private count; // number of register User function checkValidateUsers(string memory _username) public view returns (address result){// see if input username already exist if(userToAccount[_username].account == address(0)){ return userToAccount[_username].account; }else return userToAccount[_username].account; } function register(address _userAccount, address _userContract, string memory _username, string memory _password) public{ // Adding address and username to mapping, userCount++ userToAccount[_username] = User(_userAccount, _userContract, keccak256(abi.encodePacked(_password))); count++; //To log user register event emit NewUser(_userAccount, _userContract, _username); } function login(string memory _username, string memory _password) public view returns (address userAccount, address userContract){ // if username & password is correct, return user address if(keccak256(abi.encodePacked(_password)) == userToAccount[_username].password) return (userToAccount[_username].account, userToAccount[_username].contractUser); else return (address(0),address(0)); } }
TODO only manager ethereum account have access of this contract
import './Zeppelin/ownership/Ownable.sol';
12,816,049
[ 1, 6241, 1338, 3301, 13750, 822, 379, 2236, 1240, 2006, 434, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 12871, 62, 881, 84, 292, 267, 19, 995, 12565, 19, 5460, 429, 18, 18281, 13506, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; contract Sha3 { function hashArray() constant returns(bytes32) { bytes8[] memory tickers = new bytes8[](4); tickers[0] = bytes8('BTC'); tickers[1] = bytes8('ETH'); tickers[2] = bytes8('LTC'); tickers[3] = bytes8('DOGE'); return sha3(tickers); // 0x374c0504f79c1d5e6e4ded17d488802b5656bd1d96b16a568d6c324e1c04c37b } function hashPackedArray() constant returns(bytes32) { bytes8 btc = bytes8('BTC'); bytes8 eth = bytes8('ETH'); bytes8 ltc = bytes8('LTC'); bytes8 doge = bytes8('DOGE'); return sha3(btc, eth, ltc, doge); // 0xe79a6745d2205095147fd735f329de58377b2f0b9f4b81ae23e010062127f2bc } function hashAddress() constant returns(bytes32) { address account = 0x6779913e982688474f710b47e1c0506c5dca4634; return sha3(bytes20(account)); // 0x229327de236bd04ccac2efc445f1a2b63afddf438b35874b9f6fd1e6c38b0198 } function testPackedArgs() constant returns (bool) { return sha3('ab') == sha3('a', 'b'); } function hashHex() constant returns (bytes32) { return sha3(0x0a); // 0x0ef9d8f8804d174666011a394cab7901679a8944d24249fd148a6a36071151f8 } function hashInt() constant returns (bytes32) { return sha3(int(1)); } function hashNegative() constant returns (bytes32) { return sha3(int(-1)); } function hash8() constant returns (bytes32) { return sha3(1); } function hash32() constant returns (bytes32) { return sha3(uint32(1)); } function hash256() constant returns (bytes32) { return sha3(uint(1)); } function hashEth() constant returns (bytes32) { return sha3(uint(100 ether)); } function hashWei() constant returns (bytes32) { return sha3(uint(100)); } function hashMultipleArgs() constant returns (bytes32) { return sha3('a', uint(1)); } function hashString() constant returns (bytes32) { return sha3('a'); } }
0x0ef9d8f8804d174666011a394cab7901679a8944d24249fd148a6a36071151f8
function hashHex() constant returns (bytes32) { return sha3(0x0a); }
15,848,170
[ 1, 20, 92, 20, 10241, 29, 72, 28, 74, 5482, 3028, 72, 28686, 25308, 1611, 21, 69, 5520, 24, 71, 378, 7235, 24171, 7235, 69, 6675, 6334, 72, 3247, 3247, 29, 8313, 25005, 69, 26, 69, 29751, 27, 2499, 10593, 74, 28, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1651, 7037, 1435, 5381, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 6056, 23, 12, 20, 92, 20, 69, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xB15c2b8bA695212fBc975034F7F0cB914460990D/sources/ERC20.sol
Check allowance Subtract from the targeted balance Subtract from the sender's allowance Update totalSupply
function burnFrom(address _from, uint256 _value) external returns (bool success) { balanceOf[_from] = balanceOf[_from].sub(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_from, _value); return true; }
4,215,159
[ 1, 1564, 1699, 1359, 2592, 1575, 628, 326, 20715, 11013, 2592, 1575, 628, 326, 5793, 1807, 1699, 1359, 2315, 2078, 3088, 1283, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 1265, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 11013, 951, 63, 67, 2080, 65, 273, 11013, 951, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 3639, 3626, 605, 321, 24899, 2080, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x3a71DB6b085d45F7E6eF173eA01065CC01E7bd27/sources/browser/MultiSigWallet.sol
@dev Fallback function allows to deposit ether.
function () payable external { if (msg.value > 0) emit EventDeposit(msg.sender, msg.value); }
670,659
[ 1, 12355, 445, 5360, 358, 443, 1724, 225, 2437, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 8843, 429, 3903, 288, 203, 3639, 309, 261, 3576, 18, 1132, 405, 374, 13, 203, 3639, 3626, 2587, 758, 1724, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xc2B77BD20F3f49efE6D6fB0364140e557073b471/sources/contracts/Presale.sol
Greater thn 10 DAI
require(IERC20(token).balanceOf(msg.sender) >= payTokenAmount * (10 **decimals),"not Enough Balance");
7,052,899
[ 1, 20937, 286, 82, 1728, 463, 18194, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 8843, 1345, 6275, 380, 261, 2163, 2826, 31734, 3631, 6, 902, 1374, 4966, 30918, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x392384e3327218D6817ff07b76e04D995179037B/sources/contracts/EnegyPlusGirl.sol
before:0, round1:1, round2:2, public:3, after:9
function GetRoundSection() public view returns (uint) { if (block.timestamp < rd1StrTime) { return 0; return 1; return 2; return 3; } return 9; }
9,121,620
[ 1, 5771, 30, 20, 16, 3643, 21, 30, 21, 16, 3643, 22, 30, 22, 16, 1071, 30, 23, 16, 1839, 30, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 968, 11066, 5285, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 309, 261, 2629, 18, 5508, 411, 9437, 21, 1585, 950, 13, 288, 203, 5411, 327, 374, 31, 203, 5411, 327, 404, 31, 203, 5411, 327, 576, 31, 203, 5411, 327, 890, 31, 203, 3639, 289, 203, 203, 3639, 327, 2468, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } pragma solidity ^0.5.0; /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will // address keccak256("pending_owner"); // The proposed new owner mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) // keccak256("_tblock"); // // keccak256("runningTips"); // VAriable to track running tips // keccak256("currentReward"); // The current reward // keccak256("devShare"); // The amount directed towards th devShare // keccak256("currentTotalTips"); // //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } pragma solidity ^0.5.16; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event bytes32 public constant stakeAmount = 0x7be108969d31a3f0b261465c71f2b0ba9301cd914d55d9091c3b36a49d4d41b2; //keccak256("stakeAmount") /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, 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(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { TellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(TellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } pragma solidity ^0.5.16; /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Increase the dispute count by 1 uint256 disputeId = self.uintVars[keccak256("disputeCount")] + 1; self.uintVars[keccak256("disputeCount")] = disputeId; //Sets the new disputeCount as the disputeId //Ensures that a dispute is not already open for the that miner, requestId and timestamp uint256 hashId = self.disputeIdByDisputeHash[_hash]; if(hashId != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = hashId; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; hashId = disputeId; } uint256 origID = hashId; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] + 1; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] = dispRounds; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } uint256 _fee; if (_minerIndex == 2) { self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] = self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] +1; //update dispute fee for this case _fee = self.uintVars[keccak256("stakeAmount")]*self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")]; } else { _fee = self.uintVars[keccak256("disputeFee")] * dispRounds; } //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * dispRounds; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; TellorTransfer.doTransfer(self, msg.sender, address(this),_fee); //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight != 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight); } /** * @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); require(now >= disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); require(disp.reportingParty != address(0), "reporting Party is address 0"); int256 _tally = disp.tally; if (_tally > 0) { //Set the dispute state to passed/true disp.disputeVotePassed = true; } //If the vote is not a proposed fork if (disp.isPropFork == false) { //Ensure the time for voting has elapsed TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if(stakes.currentStatus == 3){ stakes.currentStatus = 4; } } else if (uint(_tally) >= ((self.uintVars[keccak256("total_supply")] * 10) / 100)) { emit NewTellorAddress(disp.proposedForkAddress); } disp.disputeUintVars[keccak256("tallyDate")] = now; disp.executed = true; emit DisputeVoteTallied(_disputeId, _tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encode(_propNewTellorAddress)); TellorTransfer.doTransfer(self, msg.sender, address(this), 100e18); //This is the fork fee (just 100 tokens flat, no refunds) self.uintVars[keccak256("disputeCount")]++; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; if(self.disputeIdByDisputeHash[_hash] != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = self.disputeIdByDisputeHash[_hash]; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; } uint256 origID = self.disputeIdByDisputeHash[_hash]; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]++; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 origID = self.disputeIdByDisputeHash[_hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; TellorStorage.Dispute storage disp = self.disputesById[lastID]; require(disp.disputeVotePassed == true, "vote needs to pass"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting for further disputes has not passed"); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { uint256 origID = self.disputeIdByDisputeHash[self.disputesById[_disputeId].hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; if(lastID == 0){ lastID = origID; } TellorStorage.Dispute storage disp = self.disputesById[origID]; TellorStorage.Dispute storage last = self.disputesById[lastID]; //disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated uint256 dispRounds = disp.disputeUintVars[keccak256("disputeRounds")]; if(dispRounds == 0){ dispRounds = 1; } uint256 _id; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - last.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (last.disputeVotePassed == true){ //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers updateMinDisputeFee(self); //Decreases the stakerCount since the miner's stake is being slashed if(stakes.currentStatus == 4){ stakes.currentStatus = 5; TellorTransfer.doTransfer(self,disp.reportedMiner,disp.reportingParty,self.uintVars[keccak256("stakeAmount")]); stakes.currentStatus =0 ; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id == 0){ _id = origID; } TellorStorage.Dispute storage disp2 = self.disputesById[_id]; //transfer fee adjusted based on number of miners if the minerIndex is not 2(official value) TellorTransfer.doTransfer(self,address(this), disp2.reportingParty, disp2.disputeUintVars[keccak256("fee")]); } } else { stakes.currentStatus = 1; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { //note we still don't put timestamp back into array (is this an issue? (shouldn't be)) _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")]; } if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id != 0){ last = self.disputesById[_id];//handling if happens during an upgrade } TellorTransfer.doTransfer(self,address(this),last.reportedMiner,self.disputesById[_id].disputeUintVars[keccak256("fee")]); } } if (disp.disputeUintVars[keccak256("minerSlot")] == 2) { self.requestDetails[disp.disputeUintVars[keccak256("requestId")]].apiUintVars[keccak256("disputeCount")]--; } } /** * @dev This function upates the minimun dispute fee as a function of the amount * of staked miners */ function updateMinDisputeFee(TellorStorage.TellorStorageStruct storage self) public { uint256 stakeAmount = self.uintVars[keccak256("stakeAmount")]; uint256 targetMiners = self.uintVars[keccak256("targetMiners")]; self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18, (stakeAmount-(stakeAmount*(SafeMath.min(targetMiners,self.uintVars[keccak256("stakerCount")])*1000)/ targetMiners)/1000)); } } pragma solidity ^0.5.16; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the max value in an array. * The zero position here is ignored. It's because * there's no null in solidity and we map each address * to an index in this array. So when we get 51 parties, * and one person is kicked out of the top 50, we * assign them a 0, and when you get mined and pulled * out of the top 50, also a 0. So then lot's of parties * will have zero as the index so we made the array run * from 1-51 with zero as nothing. * @param data is the array to calculate max from * @return max amount and its index within the array */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { maxIndex = 1; max = data[maxIndex]; for (uint256 i = 2; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. * @param data is the array to calculate min from * @return min amount and its index within the array */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } /** * @dev Returns the 5 requestsId's with the top payouts in an array. * @param data is the array to get the top 5 from * @return to 5 max amounts and their respective index within the array */ function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 0; for(uint256 j=0;j<5;j++){ max[j]= data[j+1];//max[0]=data[1] maxIndex[j] = j+1;//maxIndex[0]= 1 if(max[j] < min5){ min5 = max[j]; minI = j; } } for(uint256 i = 6; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for(uint256 j=0;j<5;j++){ if(max[j] < min5){ min5 = max[j]; minI = j; } } } } } } pragma solidity ^0.5.16; /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers TellorDispute.updateMinDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus == 2, "Miner was not locked for withdrawal"); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateMinDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount"); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } /** * @dev Getter function for the requestId being mined * @return variables for the current minin event: Challenge, 5 RequestId, difficulty and Totaltips */ function getNewCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficulty, uint256 _tip){ for(uint i=0;i<5;i++){ _requestIds[i] = self.currentMiners[i].value; } return (self.currentChallenge,_requestIds,self.uintVars[keccak256("difficulty")],self.uintVars[keccak256("currentTotalTips")]); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on top 5 requests(highest payout)-- RequestId, Totaltips */ function getNewVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { idsOnDeck = getTopRequestIDs(self); for(uint i = 0;i<5;i++){ tipsOnDeck[i] = self.requestDetails[idsOnDeck[i]].apiUintVars[keccak256("totalTip")]; } } /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function * @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called */ function getTopRequestIDs(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = Utilities.getMax5(self.requestQ); for(uint i=0;i<5;i++){ if(_max[i] != 0){ _requestIds[i] = self.requestIdByRequestQIndex[_index[i]]; } else{ _requestIds[i] = self.currentMiners[4-i].value; } } } } pragma solidity ^0.5.0; /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("_deity")] = _newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("tellorContract")] = _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) public view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * @return address requested */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256, string memory, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) { return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) { return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")], self.requestDetails[newRequestId].queryString ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to looku p * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount") bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip") bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock") bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue") bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty") bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget") bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips") bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward") bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply") bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare") bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner") bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition") bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips") bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress") bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner") bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId") event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[requestCount] + 1; if(_requestId == _count){ self.uintVars[requestCount] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 uint timeDiff = now - self.uintVars[timeOfLastNewValue]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(self.uintVars[difficulty]); _change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute bytes32 _currChallenge = self.currentChallenge; uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { for (uint i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } TellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValue] = a[2]; _request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValue); _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[totalTip] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[runningTips], _currChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue]; //payMinersRewards _payReward(self, timeDiff, miners); self.uintVars[_tBlock] ++; uint256[5] memory _topId = TellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0; self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip]; } //Issue the the next challenge _currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))); self.currentChallenge = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, self.uintVars[difficulty], self.uintVars[currentTotalTips] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { _verifyNonce(self, _nonce); _submitMiningSolution(self, _nonce, _requestId, _value); } function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) internal { //Verifying Miner Eligibility bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min"); require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong"); require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong"); require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong"); require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong"); require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong"); self.uintVars[_hashMsgSender] = now; bytes32 _currChallenge = self.currentChallenge; uint256 _slotProgress = self.uintVars[slotProgress]; //Saving the challenge information as unique by using the msg.sender //Checking and updating Miner Status require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value"); //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; _tblock.minersByValue[1][_slotProgress]= msg.sender; //Assigng directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotProgress] = _value[0]; _tblock.valuesByTimestamp[1][_slotProgress] = _value[1]; _tblock.valuesByTimestamp[2][_slotProgress] = _value[2]; _tblock.valuesByTimestamp[3][_slotProgress] = _value[3]; _tblock.valuesByTimestamp[4][_slotProgress] = _value[4]; _tblock.minersByValue[0][_slotProgress]= msg.sender; _tblock.minersByValue[1][_slotProgress]= msg.sender; _tblock.minersByValue[2][_slotProgress]= msg.sender; _tblock.minersByValue[3][_slotProgress]= msg.sender; _tblock.minersByValue[4][_slotProgress]= msg.sender; //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas newBlock(self, _nonce, _requestId); self.uintVars[slotProgress] = 0; } else{ self.uintVars[slotProgress]++; } emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge); } function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal { require(uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[difficulty] == 0 || (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev Internal function to calculate and pay rewards to miners * */ function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal { //_timeDiff is how many minutes passed since last block uint _currReward = 1e18; uint reward = _timeDiff* _currReward / 300; //each miner get's uint _tip = self.uintVars[currentTotalTips] / 10; uint _devShare = reward / 2; TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip); //update the total supply self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2); TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare); self.uintVars[currentTotalTips] = 0; } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public { require(msg.sender == self.addressVars[_owner], "Sender is not owner"); emit OwnershipProposed(self.addressVars[_owner], _pendingOwner); self.addressVars[pending_owner] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[currentTotalTips] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[requestQPosition] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[totalTip] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[totalTip]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[requestQPosition] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[requestQPosition]] += _tip; } } } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor { using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { tellor.submitMiningSolution(_nonce,_requestId, _value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { return tellor.approve(_spender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_to, _amount); } /** * @dev Sends _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) external returns (bool) { return tellor.transferFrom(_from, _to, _amount); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } /** * @dev Getter for the current variables that include the 5 requests Id's * @return the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficutly, uint256 _tip){ return tellor.getNewCurrentVariables(); } /** * @dev Getter for the top tipped 5 requests Id's * @return the 5 requestsId */ function getTopRequestIDs() external view returns(uint256[5] memory _requestIds){ return tellor.getTopRequestIDs(); } /** * @dev Getter for the 5 requests Id's next in line to get mined * @return the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { return tellor.getNewVariablesOnDeck(); } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint _disputeId) external{ return tellor.updateTellor(_disputeId); } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (uint _disputeId) external{ return tellor.unlockDisputeFee(_disputeId); } /*******************TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ // /*This is a cheat for demo purposes, will delete upon actual launch*/ // function theLazyCoon(address _address, uint _amount) external { // tellor.theLazyCoon(_address,_amount); // } // // function testSubmitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external { // // tellor.testSubmitMiningSolution(_nonce, _requestId, _value); // // } // function testSubmitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { // tellor.testSubmitMiningSolution(_nonce,_requestId, _value); // } /***************END TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ }
* @dev Gets the API struct variables that are not mappings @param _requestId to look up @return string of api to query @return string of symbol of api to query @return bytes32 hash of string @return bytes32 of the granularity(decimal places) requested @return uint of index in requestQ array @return uint of current payout/tip for this requestId/
function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); }
1,434,165
[ 1, 3002, 326, 1491, 1958, 3152, 716, 854, 486, 7990, 225, 389, 2293, 548, 358, 2324, 731, 327, 533, 434, 1536, 358, 843, 327, 533, 434, 3273, 434, 1536, 358, 843, 327, 1731, 1578, 1651, 434, 533, 327, 1731, 1578, 434, 326, 25380, 12, 12586, 12576, 13, 3764, 327, 2254, 434, 770, 316, 590, 53, 526, 327, 2254, 434, 783, 293, 2012, 19, 14587, 364, 333, 14459, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4328, 5555, 12, 21009, 280, 3245, 18, 21009, 280, 3245, 3823, 2502, 365, 16, 2254, 5034, 389, 2293, 548, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 16, 533, 3778, 16, 1731, 1578, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 29860, 280, 3245, 18, 691, 2502, 389, 2293, 273, 365, 18, 2293, 3790, 63, 67, 2293, 548, 15533, 203, 3639, 327, 261, 203, 5411, 389, 2293, 18, 2271, 780, 16, 203, 5411, 389, 2293, 18, 892, 5335, 16, 203, 5411, 389, 2293, 18, 2271, 2310, 16, 203, 5411, 389, 2293, 18, 2425, 5487, 5555, 63, 79, 24410, 581, 5034, 2932, 75, 27234, 7923, 6487, 203, 5411, 389, 2293, 18, 2425, 5487, 5555, 63, 79, 24410, 581, 5034, 2932, 2293, 53, 2555, 7923, 6487, 203, 5411, 389, 2293, 18, 2425, 5487, 5555, 63, 79, 24410, 581, 5034, 2932, 4963, 14189, 7923, 65, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol"; import "../utils/LibBytes.sol"; /** * @title ERC1077Token * @dev Mintable ERC-20 token that implements ERC-1077 functionalities to allow * signature based function execution. EIP-1077 draft contains the necessary * implementation details ; https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1077.md. * * * Notes: * - callPrefix & dataHash is replaced with _data * - to is removed (current contract) and added before from * - in operations ( create should be 2, not 0) * */ contract ERC1077Token is MintableToken { using LibBytes for bytes; // Prefix that transaction must have ERC-191 Version from to bytes constant TRANSACTION_PREFIX = abi.encode( byte(0x19), byte(0), address(this), address(this)); // bytes4(keccak256("transferFrom(address,address,uint256,uint256,bytes)"); bytes4 constant TRANSFERFROM_SIG = 0x23b872dd; // bytes4(keccak256("setApprovalForAll(address,address,bool)")); bytes4 constant SETAPPROVALFORALL_SIG = 0x367605ca; // Transaction gas // uint256 constant _TRANSACTION_GAS = 100000; // 100,000 gas for transactions // Transaction structure struct Transaction { uint256 value; // Amount of Ether to be sent bytes data; // Bytecode to be executed (function signature + encoded arguments) uint256 nonce; // Signature nonce uint256 gasPrice; // The gas price (paid in the selected token) //uint256 gasLimit; // The the maximum gas to be paid address gasToken; // Address of token to take to pay gas (leave 0 for ether) //Operation operation; // 0 for a standard call, 1 for a DelegateCall and 2 for a create opcode bytes extraData; // Extra hash for forward compatibility } // Signature structure struct Signature { uint8 v; // v variable from ECDSA signature. bytes32 r; // r variable from ECDSA signature. bytes32 s; // s variable from ECDSA signature. string sigPrefix; // Signature prefix message (e.g. "\x19Ethereum Signed Message:\n32"); } // Operation that will be executed with transaction execution (in assembly) // enum Operation { // Call, // 0 // DelegateCall, // 1 // Create // 2 // } // Mappings mapping (address => mapping(address => bool)) operators; // Operators mapping (bytes4 => bool) allowedFunctions; // Functions that can be called via ERC-1077 // Events event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // Constructor constructor() { // Allowing certain functions to be called by ERC-1077 methods allowedFunctions[TRANSFERFROM_SIG] = true; allowedFunctions[SETAPPROVALFORALL_SIG] = true; } // messages enum Error { INVALID_RECIPIENT, INVALID_SENDER, INVALID_SIGNATURE, EXECUTION_FAILED } // // Functions // // ---------------------------------- // // Modified ERC-20 // // ---------------------------------- // /** * @dev Transfer tokens from one address to another (OVERWRITTING ORIGINAL) * @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(0x0), 'INVALID_RECIPIENT'); //Verifies whether sender is _from, an operator or this contract require(msg.sender == _from || operators[_from][msg.sender] || msg.sender == address(this), 'INVALID_SENDER'); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Will set _operator operator status to true or false * @param _from Token owner * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _from, address _operator, bool _approved) public { require(msg.sender == _from || msg.sender == address(this), 'INVALID_SENDER'); // Update operator status operators[_from][_operator] = _approved; emit ApprovalForAll(_from, _operator, _approved); } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator) { return operators[_owner][_operator]; } // ---------------------------------- // // ERC-1077 // // ---------------------------------- // /** * @dev Execute a function call on the behalf of a user * @param _transaction Transaction to execute * @param _sig Signature for the given transaction */ function executeSignedTransaction(Transaction _transaction, Signature _sig) public // Can't be `external` with solc 0.24 & ABIEncoderV2 { // Extract the _from argument from the transcation data (First function argument) // THIS WILL/SHOULD BE REPLACED BY https://github.com/ethereum/solidity/pull/4390 address _from = _transaction.data.readAddress(4); // Verify if valid signature require(_from == recoverTransactionSigner(_transaction, _sig), 'INVALID_SIGNATURE'); //Execute the call require( executeCall(_transaction.data), 'EXECUTION_FAILED' ); } /** * @dev Execute the transaction based on the data passed * @param _data Transaction data * * Note: This executeCall function does not take 'to', 'value' since this implementation * of ERC-1077 is tailored to a token contract. */ function executeCall(bytes _data) internal returns (bool success) { address thisAddress = address(this); assembly { // call( gas, contractToCall, value, input start, input length, output over input, output size) success := call(70000, thisAddress, 0x0, add(_data, 0x20), mload(_data), 0, 0) } return success; } /** * @dev return the transaction hash * @param _transaction Transaction struct containing the transaction information to hash */ function getTransactionHash(Transaction _transaction) public pure returns (bytes32 transactionHash) { return keccak256( abi.encode(TRANSACTION_PREFIX, _transaction) ); } /** * @dev return signer of transaction hash * @param _transaction Transaction struct containing the transaction information to hash * @param _sig Signature structure containing the signature related variables * @return Return address of signer */ function recoverTransactionSigner( Transaction _transaction, Signature _sig) public view returns (address signer) { // Hashing arguments bytes32 hash = getTransactionHash(_transaction); // If prefix provided, hash with prefix, else ignore prefix bytes32 prefixedHash = keccak256( abi.encodePacked(_sig.sigPrefix, hash) ); // return signer recovered return recoverHashSigner(prefixedHash, _sig.r, _sig.s, _sig.v); } /** * @dev Returns the address of associated with the private key that signed _hash * @param _hash Hash that was signed. * @param _r r variable from ECDSA signature. * @param _s s variable from ECDSA signature. * @param _v v variable from ECDSA signature. * @return Address that signed the hash. */ function recoverHashSigner( bytes32 _hash, bytes32 _r, bytes32 _s, uint8 _v) public pure returns (address signer) { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (_v < 27) { _v += 27; } // Recover who signed the hash signer = ecrecover( _hash, _v, _r, _s); // Makes sure signer is not 0x0. This is to prevent signer appearing to be 0x0. assert(signer != 0x0); // Return recovered signer address return signer; } }
* @dev return the transaction hash @param _transaction Transaction struct containing the transaction information to hash/
function getTransactionHash(Transaction _transaction) public pure returns (bytes32 transactionHash) { return keccak256( abi.encode(TRANSACTION_PREFIX, _transaction) ); }
12,665,007
[ 1, 2463, 326, 2492, 1651, 225, 389, 7958, 5947, 1958, 4191, 326, 2492, 1779, 358, 1651, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 15674, 2310, 12, 3342, 389, 7958, 13, 203, 1377, 1071, 16618, 1135, 261, 3890, 1578, 2492, 2310, 13, 203, 225, 288, 203, 565, 327, 225, 417, 24410, 581, 5034, 12, 24126, 18, 3015, 12, 22364, 67, 6307, 16, 389, 7958, 13, 11272, 7010, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x1F6857faB7cbc8aB1ae4A1e2F264b82dF7E3FE75/sources/contracts/CaveDinoStaking.sol
@dev Initiliazes the contract, like a constructor.
) external initializer { __ReentrancyGuard_init(); __ERC2771Context_init_unchained(_trustedForwarders); rewardToken = _rewardToken; __Staking1155_init(_edition); _setDefaultTimeUnit(_defaultTimeUnit); _setDefaultRewardsPerUnitTime(_defaultRewardsPerUnitTime); _setupContractURI(_contractURI); _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); }
1,952,134
[ 1, 2570, 330, 1155, 94, 281, 326, 6835, 16, 3007, 279, 3885, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3903, 12562, 288, 203, 3639, 1001, 426, 8230, 12514, 16709, 67, 2738, 5621, 203, 3639, 1001, 654, 39, 22, 4700, 21, 1042, 67, 2738, 67, 4384, 8707, 24899, 25247, 8514, 414, 1769, 203, 203, 3639, 19890, 1345, 273, 389, 266, 2913, 1345, 31, 203, 3639, 1001, 510, 6159, 2499, 2539, 67, 2738, 24899, 329, 608, 1769, 203, 3639, 389, 542, 1868, 950, 2802, 24899, 1886, 950, 2802, 1769, 203, 3639, 389, 542, 1868, 17631, 14727, 2173, 2802, 950, 24899, 1886, 17631, 14727, 2173, 2802, 950, 1769, 203, 203, 3639, 389, 8401, 8924, 3098, 24899, 16351, 3098, 1769, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 1886, 4446, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/AssetHelpers.sol"; import "./Moartroller.sol"; import "./SimplePriceOracle.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers { /** * @notice get the maximum asset value that can be still optimized. * @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value' * which is helpful to recalculate how much of this protection can be optimized again */ function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){ uint returnValue; uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments); uint totalProtectionLockedValue; (totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments); if(hypotheticalOptimizableValue <= totalProtectionLockedValue){ returnValue = 0; } else{ returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue); } return returnValue; } /** * @notice get the maximum value of an asset that can be optimized by protection for the given user * @dev optimizable = asset value * MPC * @return the hypothetical optimizable value * TODO: replace hardcoded 1e18 values */ function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) { uint assetValue = div_( mul_( div_( mul_( arguments.asset.balanceOf(arguments.account), arguments.asset.exchangeRateStored() ), 1e18 ), arguments.oracle.getUnderlyingPrice(arguments.asset) ), getAssetDecimalsMantissa(arguments.asset.getUnderlying()) ); uint256 hypotheticalOptimizableValue = div_( mul_( assetValue, arguments.asset.maxProtectionComposition() ), arguments.asset.maxProtectionCompositionMantissa() ); return hypotheticalOptimizableValue; } /** * @dev gets all locked protections values with mark to market value. Used by Moartroller. */ function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) { uint _lockedValue = 0; uint _markToMarket = 0; uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying()); for (uint j = 0; j < _protectionCount; j++) { uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j); bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId); if(protectionIsAlive){ _lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId)); uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset); uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId); if( assetSpotPrice > protectionStrikePrice) { _markToMarket = _markToMarket + div_( mul_( div_( mul_( assetSpotPrice - protectionStrikePrice, arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId) ), getAssetDecimalsMantissa(arguments.asset.underlying()) ), arguments.collateralFactorMantissa ), 1e18 ); } } } return (_lockedValue , _markToMarket); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "../MToken.sol"; import "../MProtection.sol"; import "../Interfaces/PriceOracle.sol"; interface LiquidityMathModelInterface { struct LiquidityMathArgumentsSet { MToken asset; address account; uint collateralFactorMantissa; MProtection cprotection; PriceOracle oracle; } function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint); function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint); function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Utils/ErrorReporter.sol"; import "./Utils/Exponential.sol"; import "./Interfaces/EIP20Interface.sol"; import "./MTokenStorage.sol"; import "./Interfaces/MTokenInterface.sol"; import "./Interfaces/MProxyInterface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; /** * @title MOAR's MToken Contract * @notice Abstract base for MTokens * @author MOAR */ abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage { /** * @notice Indicator that this is a MToken contract (for inspection) */ bool public constant isMToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when moartroller is changed */ event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Max protection composition value updated event */ event MpcUpdated(uint newValue); /** * @notice Initialize the money market * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function init(Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "not_admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "too_low"); // Set the moartroller uint err = _setMoartroller(moartroller_); require(err == uint(Error.NO_ERROR), "setting moartroller failed"); // Initialize block number and borrow index (block number mocks depend on moartroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; maxProtectionComposition = 5000; maxProtectionCompositionMantissa = 1e4; reserveFactorMaxMantissa = 1e18; borrowRateMaxMantissa = 0.0005e16; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srmTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srmTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // moartroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @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, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @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, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @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 (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external virtual override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external virtual override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external virtual override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external virtual override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance_calculation_failed"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by moartroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) { uint mTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public virtual view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public virtual nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public virtual view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external virtual override view returns (uint) { return getCashPrior(); } function getRealBorrowIndex() public view returns (uint) { uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); Exp memory simpleInterestFactor; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor"); (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex"); return borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; AccrueInterestTempStorage memory temp; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = temp.borrowIndexNew; totalBorrows = temp.totalBorrowsNew; totalReserves = temp.totalReservesNew; if(temp.splitedReserves_2 > 0){ address mProxy = moartroller.mProxy(); EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2); MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2); } /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives mTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the mToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of mTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* * We calculate the new total supply of mTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems mTokens 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 receive from redeeming mTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems mTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) { require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing"); uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ //unused function // moartroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ /* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */ if (repayAmount == uint(-1)) { require(tx.origin == borrower, "specify a precise amount"); vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = mTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify mTokenCollateral market's block number equals current block number */ if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower); require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(mTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another mToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. * Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external virtual override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new moartroller for the market * @dev Admin function to set a new moartroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK); } Moartroller oldMoartroller = moartroller; // Ensure invoke moartroller.isMoartroller() returns true require(newMoartroller.isMoartroller(), "not_moartroller"); // Set market's moartroller to newMoartroller moartroller = newMoartroller; // Emit NewMoartroller(oldMoartroller, newMoartroller) emit NewMoartroller(oldMoartroller, newMoartroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } reserveSplitFactorMantissa = newReserveSplitFactorMantissa; return uint(Error.NO_ERROR); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModelInterface oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "not_interest_model"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /** * @notice Sets new value for max protection composition parameter * @param newMPC New value of MPC * @return uint 0=success, otherwise a failure */ function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); } /** * @notice Returns address of underlying token * @return address of underlying token */ function getUnderlying() external override view returns(address){ return underlying; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal virtual view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; contract MoartrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, MOARTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_PROTECTION_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, MOARTROLLER_REJECTION, MOARTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_MOARTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_MOARTROLLER_REJECTION, LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_MOARTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_MOARTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_MOARTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_MOARTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_MOARTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract LiquidityMathModelErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, PRICE_ERROR, SNAPSHOT_ERROR } enum FailureInfo { ORACLE_PRICE_CHECK_FAILED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../Interfaces/EIP20Interface.sol"; contract AssetHelpers { /** * @dev return asset decimals mantissa. Returns 1e18 if ETH */ function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){ uint assetDecimals = 1e18; if (assetAddress != address(0)) { EIP20Interface token = EIP20Interface(assetAddress); assetDecimals = 10 ** uint256(token.decimals()); } return assetDecimals; } } // SPDX-License-Identifier: BSD-3-Clause // Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/MoartrollerInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Interfaces/MProxyInterface.sol"; import "./MoartrollerStorage.sol"; import "./Governance/UnionGovernanceToken.sol"; import "./MProtection.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./LiquidityMathModelV1.sol"; import "./Utils/SafeEIP20.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title MOAR's Moartroller Contract * @author MOAR */ contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable { using SafeEIP20 for EIP20Interface; /// @notice Indicator that this is a Moartroller contract (for inspection) bool public constant isMoartroller = true; /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when protection is changed event NewCProtection(MProtection oldCProtection, MProtection newCProtection); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPausedMToken(MToken mToken, string action, bool pauseState); /// @notice Emitted when a new MOAR speed is calculated for a market event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed); /// @notice Emitted when a new MOAR speed is set for a contributor event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when MOAR is distributed to a supplier event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex); /// @notice Emitted when MOAR is distributed to a borrower event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when MOAR is granted by admin event MoarGranted(address recipient, uint amount); event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel); event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel); /// @notice The initial MOAR index for a market uint224 public constant moarInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // Custom initializer function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer { admin = msg.sender; liquidityMathModel = mathModel; liquidationModel = lqdModel; rewardClaimEnabled = false; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external override returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param 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) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) { return uint(Error.MOARTROLLER_MISMATCH); } // Keep the flywheel moving updateMoarSupplyIndex(mTokenCollateral); distributeSupplierMoar(mTokenCollateral, borrower); distributeSupplierMoar(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, src); distributeSupplierMoar(mToken, dst); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; address _account = account; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals())); // Pre-compute a conversion factor from tokens -> dai (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // Protection value calculation sumCollateral += protectionValueLocked // Mark to market value calculation sumCollateral += markToMarketValue uint protectionValueLocked; uint markToMarketValue; (protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle)); if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) { vars.sumCollateral = 0; } else { vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor)); } vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked); vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); _account = account; } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Returns the value of possible optimization left for asset * @param asset The MToken address * @param account The owner of asset * @return The value of possible optimization */ function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getMaxOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } /** * @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset * @param asset The MToken address * @param account The owner of asset * @return The amount of hypothetical optimization */ function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getHypotheticalOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) { return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens( LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet( oracle, this, mTokenBorrowed, mTokenCollateral, actualRepayAmount, account, liquidationIncentiveMantissa ) ); } /** * @notice Returns the amount of a specific asset that is locked under all c-ops * @param asset The MToken address * @param account The owner of asset * @return The amount of asset locked under c-ops */ function getUserLockedAmount(MToken asset, address account) public override view returns(uint) { uint protectionLockedAmount; address currency = asset.underlying(); uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency); for (uint i = 0; i < numOfProtections; i++) { uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i); if(cprotection.isProtectionAlive(cProtectionId)){ protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId); } } return protectionLockedAmount; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the moartroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the moartroller PriceOracle oldOracle = oracle; // Set moartroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a new CProtection that is allowed to use as a collateral optimisation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setProtection(address newCProtection) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } MProtection oldCProtection = cprotection; cprotection = MProtection(newCProtection); // Emit NewPriceOracle(oldOracle, newOracle) emit NewCProtection(oldCProtection, cprotection); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // TODO: this check is temporary switched off. we can make exception for UNN later // Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // // // Check collateral factor <= 0.9 // Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); // if (lessThanExp(highLimit, newCollateralFactorExp)) { // return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); // } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } function _setRewardClaimEnabled(bool status) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); rewardClaimEnabled = status; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } mToken.isMToken(); // Sanity check to make sure its really a MToken // Note that isMoared is not in active use anymore markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0}); tokenAddressToMToken[address(mToken.underlying())] = mToken; _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == moartrollerImplementation; } /*** MOAR Distribution ***/ /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal { uint currentMoarSpeed = moarSpeeds[address(mToken)]; if (currentMoarSpeed != 0) { // note that MOAR speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarSupplyIndex(address(mToken)); updateMoarBorrowIndex(address(mToken), borrowIndex); } else if (moarSpeed != 0) { // Add the MOAR market Market storage market = markets[address(mToken)]; require(market.isListed == true, "MOAR market is not listed"); if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) { moarSupplyState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) { moarBorrowState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentMoarSpeed != moarSpeed) { moarSpeeds[address(mToken)] = moarSpeed; emit MoarSpeedUpdated(mToken, moarSpeed); } } /** * @notice Accrue MOAR to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMoarSupplyIndex(address mToken) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; uint supplySpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = MToken(mToken).totalSupply(); uint moarAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); moarSupplyState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue MOAR to the market by updating the borrow index * @param mToken The market whose borrow index to update */ function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; uint borrowSpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex); uint moarAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); moarBorrowState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate MOAR accrued by a supplier and possibly transfer it to them * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOAR to */ function distributeSupplierMoar(address mToken, address supplier) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]}); moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = moarInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = MToken(mToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta); moarAccrued[supplier] = supplierAccrued; emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate MOAR accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOAR to */ function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]}); moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta); moarAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate additional accrued MOAR for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint moarSpeed = moarContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && moarSpeed > 0) { uint newAccrued = mul_(deltaBlocks, moarSpeed); uint contributorAccrued = add_(moarAccrued[contributor], newAccrued); moarAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the MOAR accrued by holder in all markets * @param holder The address to claim MOAR for */ function claimMoarReward(address holder) public { return claimMoar(holder, allMarkets); } /** * @notice Claim all the MOAR accrued by holder in the specified markets * @param holder The address to claim MOAR for * @param mTokens The list of markets to claim MOAR in */ function claimMoar(address holder, MToken[] memory mTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimMoar(holders, mTokens, true, true); } /** * @notice Claim all MOAR accrued by the holders * @param holders The addresses to claim MOAR for * @param mTokens The list of markets to claim MOAR in * @param borrowers Whether or not to claim MOAR earned by borrowing * @param suppliers Whether or not to claim MOAR earned by supplying */ function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public { require(rewardClaimEnabled, "reward claim is disabled"); for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; require(markets[address(mToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarBorrowIndex(address(mToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerMoar(address(mToken), holders[j], borrowIndex); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } if (suppliers == true) { updateMoarSupplyIndex(address(mToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierMoar(address(mToken), holders[j]); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } } } /** * @notice Transfer MOAR to the user * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param user The address of the user to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer * @return The amount of MOAR which was NOT transferred to the user */ function grantMoarInternal(address user, uint amount) internal returns (uint) { EIP20Interface moar = EIP20Interface(getMoarAddress()); uint moarRemaining = moar.balanceOf(address(this)); if (amount > 0 && amount <= moarRemaining) { moar.approve(mProxy, amount); MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount); return 0; } return amount; } /*** MOAR Distribution Admin ***/ /** * @notice Transfer MOAR to the recipient * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param recipient The address of the recipient to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer */ function _grantMoar(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant MOAR"); uint amountLeft = grantMoarInternal(recipient, amount); require(amountLeft == 0, "insufficient MOAR for grant"); emit MoarGranted(recipient, amount); } /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function _setMoarSpeed(MToken mToken, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); setMoarSpeedInternal(mToken, moarSpeed); } /** * @notice Set MOAR speed for a single contributor * @param contributor The contributor whose MOAR speed to update * @param moarSpeed New MOAR speed for contributor */ function _setContributorMoarSpeed(address contributor, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); // note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (moarSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } moarContributorSpeeds[contributor] = moarSpeed; emit ContributorMoarSpeedUpdated(contributor, moarSpeed); } /** * @notice Set liquidity math model implementation * @param mathModel the math model implementation */ function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel; liquidityMathModel = mathModel; emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel)); } /** * @notice Set liquidation model implementation * @param newLiquidationModel the liquidation model implementation */ function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public { require(msg.sender == admin, "only admin can set liquidation model implementation"); LiquidationModelInterface oldLiquidationModel = liquidationModel; liquidationModel = newLiquidationModel; emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel)); } function _setMoarToken(address moarTokenAddress) public { require(msg.sender == admin, "only admin can set MOAR token address"); moarToken = moarTokenAddress; } function _setMProxy(address mProxyAddress) public { require(msg.sender == admin, "only admin can set MProxy address"); mProxy = mProxyAddress; } /** * @notice Add new privileged address * @param privilegedAddress address to add */ function _addPrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); privilegedAddresses[privilegedAddress] = 1; } /** * @notice Remove privileged address * @param privilegedAddress address to remove */ function _removePrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); delete privilegedAddresses[privilegedAddress]; } /** * @notice Check if address if privileged * @param privilegedAddress address to check */ function isPrivilegedAddress(address privilegedAddress) public view returns (bool) { return privilegedAddresses[privilegedAddress] == 1; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the MOAR token * @return The address of MOAR */ function getMoarAddress() public view returns (address) { return moarToken; } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/PriceOracle.sol"; import "./CErc20.sol"; /** * Temporary simple price feed */ contract SimplePriceOracle is PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(MToken mToken) public override view returns (uint) { if (compareStrings(mToken.symbol(), "mDAI")) { return 1e18; } else { return prices[address(MErc20(address(mToken)).underlying())]; } } function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public { address asset = address(MErc20(address(mToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // 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.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./Interfaces/CopMappingInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Moartroller.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/AssetHelpers.sol"; import "./MToken.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MProtection Contract * @notice Collateral optimization ERC-721 wrapper * @author MOAR */ contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; /** * @notice Event emitted when new MProtection token is minted */ event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime); /** * @notice Event emitted when MProtection token is redeemed */ event Redeem(address redeemer, uint tokenId, uint underlyingTokenId); /** * @notice Event emitted when MProtection token changes its locked value */ event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue); /** * @notice Event emitted when maturity window parameter is changed */ event MaturityWindowUpdated(uint newMaturityWindow); Counters.Counter private _tokenIds; address private _copMappingAddress; address private _moartrollerAddress; mapping (uint256 => uint256) private _underlyingProtectionTokensMapping; mapping (uint256 => uint256) private _underlyingProtectionLockedValue; mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping; uint256 public _maturityWindow; struct ProtectionMappedData{ address pool; address underlyingAsset; uint256 amount; uint256 strike; uint256 premium; uint256 lockedValue; uint256 totalValue; uint issueTime; uint expirationTime; bool isProtectionAlive; } /** * @notice Constructor for MProtection contract * @param copMappingAddress The address of data mapper for C-OP * @param moartrollerAddress The address of the Moartroller */ function initialize(address copMappingAddress, address moartrollerAddress) public initializer { __Ownable_init(); __ERC721_init("c-uUNN OC-Protection", "c-uUNN"); _copMappingAddress = copMappingAddress; _moartrollerAddress = moartrollerAddress; _setMaturityWindow(10800); // 3 hours default } /** * @notice Returns C-OP mapping contract */ function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); } /** * @notice Mint new MProtection token * @param underlyingTokenId Id of C-OP token that will be deposited * @return ID of minted MProtection token */ function mint(uint256 underlyingTokenId) public returns (uint256) { return mintFor(underlyingTokenId, msg.sender); } /** * @notice Mint new MProtection token for specified address * @param underlyingTokenId Id of C-OP token that will be deposited * @param receiver Address that will receive minted Mprotection token * @return ID of minted MProtection token */ function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256) { CopMappingInterface copMappingInstance = copMapping(); ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); addUProtectionIndexes(receiver, newItemId, underlyingTokenId); emit Mint( receiver, newItemId, underlyingTokenId, copMappingInstance.getUnderlyingAsset(underlyingTokenId), copMappingInstance.getUnderlyingAmount(underlyingTokenId), copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId), copMappingInstance.getUnderlyingDeadline(underlyingTokenId) ); return newItemId; } /** * @notice Redeem C-OP token * @param tokenId Id of MProtection token that will be withdrawn * @return ID of redeemed C-OP token */ function redeem(uint256 tokenId) external returns (uint256) { require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved"); uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId); removeProtectionIndexes(tokenId); _burn(tokenId); emit Redeem(msg.sender, tokenId, underlyingTokenId); return underlyingTokenId; } /** * @notice Returns set of C-OP data * @param tokenId Id of MProtection token * @return ProtectionMappedData struct filled with C-OP data */ function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){ ProtectionMappedData memory data; (address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId); data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId)); return data; } /** * @notice Returns underlying token ID * @param tokenId Id of MProtection token */ function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){ return _underlyingProtectionTokensMapping[tokenId]; } /** * @notice Returns size of C-OPs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].length(); } /** * @notice Returns list of C-OP IDs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].at(index); } /** * @notice Checks if address is owner of MProtection * @param owner Address of potential owner to check * @param tokenId ID of MProtection to check */ function isUserProtection(address owner, uint256 tokenId) public view returns(bool) { if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){ return true; } return owner == ownerOf(tokenId); } /** * @notice Checks if MProtection is stil alive * @param tokenId ID of MProtection to check */ function isProtectionAlive(uint256 tokenId) public view returns(bool) { uint256 deadline = getUnderlyingDeadline(tokenId); return (deadline - _maturityWindow) > now; } /** * @notice Creates appropriate indexes for C-OP * @param owner C-OP owner address * @param tokenId ID of MProtection * @param underlyingTokenId ID of C-OP */ function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{ address currency = copMapping().getUnderlyingAsset(underlyingTokenId); _underlyingProtectionTokensMapping[tokenId] = underlyingTokenId; _protectionCurrencyMapping[owner][currency].add(tokenId); } /** * @notice Remove indexes for C-OP * @param tokenId ID of MProtection */ function removeProtectionIndexes(uint256 tokenId) private{ address owner = ownerOf(tokenId); address currency = getUnderlyingAsset(tokenId); _underlyingProtectionTokensMapping[tokenId] = 0; _protectionCurrencyMapping[owner][currency].remove(tokenId); } /** * @notice Returns C-OP total value * @param tokenId ID of MProtection */ function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); return div_( mul_( getUnderlyingStrikePrice(tokenId), getUnderlyingAmount(tokenId) ), assetDecimalsMantissa ); } /** * @notice Returns C-OP locked value * @param tokenId ID of MProtection */ function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){ return _underlyingProtectionLockedValue[tokenId]; } /** * @notice get the amount of underlying asset that is locked * @param tokenId CProtection tokenId * @return amount locked */ function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); // calculates total protection value uint256 protectionValue = div_( mul_( getUnderlyingAmount(tokenId), getUnderlyingStrikePrice(tokenId) ), assetDecimalsMantissa ); // return value is lockedValue / totalValue * amount return div_( mul_( getUnderlyingAmount(tokenId), div_( mul_( _underlyingProtectionLockedValue[tokenId], 1e18 ), protectionValue ) ), 1e18 ); } /** * @notice Locks the given protection value as collateral optimization * @param tokenId The MProtection token id * @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization * @return locked protection value * TODO: convert semantic errors to standarized error codes */ function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) { //check if the protection belongs to the caller require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION"); address currency = getUnderlyingAsset(tokenId); Moartroller moartroller = Moartroller(_moartrollerAddress); MToken mToken = moartroller.tokenAddressToMToken(currency); require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE"); uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId); uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId)); // add protection locked value if any uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId); if ( protectionLockedValue > 0) { maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue); } uint valueToLock; if (value != 0) { // check if lock value is at most max optimizable value require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE"); // check if lock value is at most protection total value require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE"); valueToLock = value; } else { // if we want to lock maximum protection value let's lock the value that is at most max optimizable value if (protectionTotalValue > maxOptimizableValue) { valueToLock = maxOptimizableValue; } else { valueToLock = protectionTotalValue; } } _underlyingProtectionLockedValue[tokenId] = valueToLock; emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock); return valueToLock; } function _setCopMapping(address newMapping) public onlyOwner { _copMappingAddress = newMapping; } function _setMoartroller(address newMoartroller) public onlyOwner { _moartrollerAddress = newMoartroller; } function _setMaturityWindow(uint256 maturityWindow) public onlyOwner { emit MaturityWindowUpdated(maturityWindow); _maturityWindow = maturityWindow; } // MAPPINGS function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getProtectionData(underlyingTokenId); } function getUnderlyingAsset(uint256 tokenId) public view returns (address){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAsset(underlyingTokenId); } function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAmount(underlyingTokenId); } function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingStrikePrice(underlyingTokenId); } function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingDeadline(underlyingTokenId); } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface PriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(MToken mToken) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256); /** * @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 success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @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 success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @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 (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; abstract contract MTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @dev EIP-20 token name for this token */ string public name; /** * @dev EIP-20 token symbol for this token */ string public symbol; /** * @dev EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Underlying asset for this MToken */ address public underlying; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal borrowRateMaxMantissa; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal reserveFactorMaxMantissa; /** * @dev Administrator for this contract */ address payable public admin; /** * @dev Pending administrator for this contract */ address payable public pendingAdmin; /** * @dev Contract which oversees inter-mToken operations */ Moartroller public moartroller; /** * @dev Model which tells what the current interest rate should be */ AbstractInterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @dev Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @dev Fraction of reserves currently set aside for other usage */ uint public reserveSplitFactorMantissa; /** * @dev Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @dev Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @dev Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @dev Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @dev Total number of tokens in circulation */ uint public totalSupply; /** * @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000 */ uint public maxProtectionComposition; /** * @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5 */ uint public maxProtectionCompositionMantissa; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; struct ProtectionUsage { uint256 protectionValueUsed; } /** * @dev Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; mapping (uint256 => ProtectionUsage) protectionsUsed; } struct AccrueInterestTempStorage{ uint interestAccumulated; uint reservesAdded; uint splitedReserves_1; uint splitedReserves_2; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) public accountBorrows; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./EIP20Interface.sol"; interface MTokenInterface { /*** User contract ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function getUnderlying() external view returns(address); function sweepToken(EIP20Interface token) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface MProxyInterface { function proxyClaimReward(address asset, address recipient, uint amount) external; function proxySplitReserves(address asset, uint amount) external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/InterestRateModelInterface.sol"; abstract contract AbstractInterestRateModel is InterestRateModelInterface { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Careful Math * @author MOAR * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; import "../Utils/ExponentialNoError.sol"; interface MoartrollerInterface { /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; ExponentialNoError.Exp collateralFactor; ExponentialNoError.Exp exchangeRate; ExponentialNoError.Exp oraclePrice; ExponentialNoError.Exp tokensToDenom; } /*** Assets You Are In ***/ function enterMarkets(address[] calldata mTokens) external returns (uint[] memory); function exitMarket(address mToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeUserTokens( address mTokenBorrowed, address mTokenCollateral, uint repayAmount, address account) external view returns (uint, uint); function getUserLockedAmount(MToken asset, address account) external view returns(uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface Versionable { function getContractVersion() external pure returns (string memory); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "./MProtection.sol"; abstract contract UnitrollerAdminStorage { /** * @dev Administrator for this contract */ address public admin; /** * @dev Pending administrator for this contract */ address public pendingAdmin; /** * @dev Active brains of Unitroller */ address public moartrollerImplementation; /** * @dev Pending brains of Unitroller */ address public pendingMoartrollerImplementation; } contract MoartrollerV1Storage is UnitrollerAdminStorage { /** * @dev Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @dev Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @dev Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @dev Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => MToken[]) public accountAssets; } contract MoartrollerV2Storage is MoartrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives MOAR bool isMoared; } /** * @dev Official mapping of mTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @dev The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract MoartrollerV3Storage is MoartrollerV2Storage { struct MoarMarketState { // The market's last updated moarBorrowIndex or moarSupplyIndex uint224 index; // The block number the index was last updated at uint32 block; } /// @dev A list of all markets MToken[] public allMarkets; /// @dev The rate at which the flywheel distributes MOAR, per block uint public moarRate; /// @dev The portion of moarRate that each market currently receives mapping(address => uint) public moarSpeeds; /// @dev The MOAR market supply state for each market mapping(address => MoarMarketState) public moarSupplyState; /// @dev The MOAR market borrow state for each market mapping(address => MoarMarketState) public moarBorrowState; /// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarSupplierIndex; /// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarBorrowerIndex; /// @dev The MOAR accrued but not yet transferred to each user mapping(address => uint) public moarAccrued; } contract MoartrollerV4Storage is MoartrollerV3Storage { // @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract MoartrollerV5Storage is MoartrollerV4Storage { /// @dev The portion of MOAR that each contributor receives per block mapping(address => uint) public moarContributorSpeeds; /// @dev Last block at which a contributor's MOAR rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract MoartrollerV6Storage is MoartrollerV5Storage { /** * @dev Moar token address */ address public moarToken; /** * @dev MProxy address */ address public mProxy; /** * @dev CProtection contract which can be used for collateral optimisation */ MProtection public cprotection; /** * @dev Mapping for basic token address to mToken */ mapping(address => MToken) public tokenAddressToMToken; /** * @dev Math model for liquidity calculation */ LiquidityMathModelInterface public liquidityMathModel; /** * @dev Liquidation model for liquidation related functions */ LiquidationModelInterface public liquidationModel; /** * @dev List of addresses with privileged access */ mapping(address => uint) public privilegedAddresses; /** * @dev Determines if reward claim feature is enabled */ bool public rewardClaimEnabled; } // Copyright (c) 2020 The UNION Protocol Foundation // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @title UNION Protocol Governance Token * @dev Implementation of the basic standard token. */ contract UnionGovernanceToken is AccessControl, IERC20 { using Address for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /** * @notice Struct for marking number of votes from a given block * @member from * @member votes */ struct VotingCheckpoint { uint256 from; uint256 votes; } /** * @notice Struct for locked tokens * @member amount * @member releaseTime * @member votable */ struct LockedTokens{ uint amount; uint releaseTime; bool votable; } /** * @notice Struct for EIP712 Domain * @member name * @member version * @member chainId * @member verifyingContract * @member salt */ struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } /** * @notice Struct for EIP712 VotingDelegate call * @member owner * @member delegate * @member nonce * @member expirationTime */ struct VotingDelegate { address owner; address delegate; uint256 nonce; uint256 expirationTime; } /** * @notice Struct for EIP712 Permit call * @member owner * @member spender * @member value * @member nonce * @member deadline */ struct Permit { address owner; address spender; uint256 value; uint256 nonce; uint256 deadline; } /** * @notice Vote Delegation Events */ event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate); event VotingDelegateRemoved(address indexed _owner); /** * @notice Vote Balance Events * Emmitted when a delegate account's vote balance changes at the time of a written checkpoint */ event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance); /** * @notice Transfer/Allocator Events */ event TransferStatusChanged(bool _newTransferStatus); /** * @notice Reversion Events */ event ReversionStatusChanged(bool _newReversionSetting); /** * @notice EIP-20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice EIP-20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed _from, uint256 _value); event AddressPermitted(address indexed _account); event AddressRestricted(address indexed _account); /** * @dev AccessControl recognized roles */ bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE"); bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN"); bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT"); bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK"); bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED"); bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST"); bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( "DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)" ); //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; address private constant BURN_ADDRESS = address(0); address public UPGT_CONTRACT_ADDRESS; /** * @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting. */ bytes32 public immutable EIP712DOMAIN_SEPARATOR; /** * @dev EIP-20 token name */ string public name = "UNION Protocol Governance Token"; /** * @dev EIP-20 token symbol */ string public symbol = "UNN"; /** * @dev EIP-20 token decimals */ uint8 public decimals = 18; /** * @dev Contract version */ string public constant version = '0.0.1'; /** * @dev Initial amount of tokens */ uint256 private uint256_initialSupply = 100000000000 * 10**18; /** * @dev Total amount of tokens */ uint256 private uint256_totalSupply; /** * @dev Chain id */ uint256 private uint256_chain_id; /** * @dev general transfer restricted as function of public sale not complete */ bool private b_canTransfer = false; /** * @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions. */ bool private b_revert = false; //false allows false return values /** * @dev Locked destinations list */ mapping(address => bool) private m_lockedDestinations; /** * @dev EIP-20 allowance and balance maps */ mapping(address => mapping(address => uint256)) private m_allowances; mapping(address => uint256) private m_balances; mapping(address => LockedTokens[]) private m_lockedBalances; /** * @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712 */ mapping(address => uint256) private m_nonces; /** * @dev delegated account may for off-line vote delegation */ mapping(address => address) private m_delegatedAccounts; /** * @dev delegated account inverse map is needed to live calculate voting power */ mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap; /** * @dev indexed mapping of vote checkpoints for each account */ mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints; /** * @dev mapping of account addrresses to voting checkpoints */ mapping(address => uint256) private m_accountVotingCheckpoints; /** * @dev Contructor for the token * @param _owner address of token contract owner * @param _initialSupply of tokens generated by this contract * Sets Transfer the total suppply to the owner. * Sets default admin role to the owner. * Sets ROLE_ALLOCATE to the owner. * Sets ROLE_GOVERN to the owner. * Sets ROLE_MINT to the owner. * Sets EIP 712 Domain Separator. */ constructor(address _owner, uint256 _initialSupply) public { //set internal contract references UPGT_CONTRACT_ADDRESS = address(this); //setup roles using AccessControl _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLE_ADMIN, _owner); _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(ROLE_ALLOCATE, _owner); _setupRole(ROLE_ALLOCATE, _msgSender()); _setupRole(ROLE_TRUSTED, _owner); _setupRole(ROLE_TRUSTED, _msgSender()); _setupRole(ROLE_GOVERN, _owner); _setupRole(ROLE_MINT, _owner); _setupRole(ROLE_LOCK, _owner); _setupRole(ROLE_TEST, _owner); m_balances[_owner] = _initialSupply; uint256_totalSupply = _initialSupply; b_canTransfer = false; uint256_chain_id = _getChainId(); EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({ name : name, version : version, chainId : uint256_chain_id, verifyingContract : address(this), salt : keccak256(abi.encodePacked(name)) } )); emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply); } /** * @dev Sets transfer status to lock token transfer * @param _canTransfer value can be true or false. * disables transfer when set to false and enables transfer when true * Only a member of ADMIN role can call to change transfer status */ function setCanTransfer(bool _canTransfer) public { if(hasRole(ROLE_ADMIN, _msgSender())){ b_canTransfer = _canTransfer; emit TransferStatusChanged(_canTransfer); } } /** * @dev Gets status of token transfer lock * @return true or false status of whether the token can be transfered */ function getCanTransfer() public view returns (bool) { return b_canTransfer; } /** * @dev Sets transfer reversion status to either return false or throw on error * @param _reversion value can be true or false. * disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true * Only a member of ADMIN role can call to change transfer reversion status */ function setReversion(bool _reversion) public { if(hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TEST, _msgSender()) ) { b_revert = _reversion; emit ReversionStatusChanged(_reversion); } } /** * @dev Gets status of token transfer reversion * @return true or false status of whether the token transfer failures return false or are reverted */ function getReversion() public view returns (bool) { return b_revert; } /** * @dev retrieve current chain id * @return chain id */ function getChainId() public pure returns (uint256) { return _getChainId(); } /** * @dev Retrieve current chain id * @return chain id */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Retrieve total supply of tokens * @return uint256 total supply of tokens */ function totalSupply() public view override returns (uint256) { return uint256_totalSupply; } /** * Balance related functions */ /** * @dev Retrieve balance of a specified account * @param _account address of account holding balance * @return uint256 balance of the specified account address */ function balanceOf(address _account) public view override returns (uint256) { return m_balances[_account].add(_calculateReleasedBalance(_account)); } /** * @dev Retrieve locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); } /** * @dev Retrieve lenght of locked balance array for specific address * @param _account address of account holding locked balance * @return uint256 locked balance array lenght */ function getLockedTokensListSize(address _account) public view returns (uint256){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); return m_lockedBalances[_account].length; } /** * @dev Retrieve locked tokens struct from locked balance array for specific address * @param _account address of account holding locked tokens * @param _index index in array with locked tokens position * @return amount of locked tokens * @return releaseTime descibes time when tokens will be unlocked * @return votable flag is describing votability of tokens */ function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index"); LockedTokens storage lockedTokens = m_lockedBalances[_account][_index]; return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable); } /** * @dev Calculates locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function _calculateLockedBalance(address _account) private view returns (uint256) { uint256 lockedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime > block.timestamp){ lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount); } } return lockedBalance; } /** * @dev Calculates released balance of a specified account * @param _account address of account holding released balance * @return uint256 released balance of the specified account address */ function _calculateReleasedBalance(address _account) private view returns (uint256) { uint256 releasedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount); } } return releasedBalance; } /** * @dev Calculates locked votable balance of a specified account * @param _account address of account holding locked votable balance * @return uint256 locked votable balance of the specified account address */ function _calculateLockedVotableBalance(address _account) private view returns (uint256) { uint256 lockedVotableBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].votable == true){ lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount); } } return lockedVotableBalance; } /** * @dev Moves released balance to normal balance for a specified account * @param _account address of account holding released balance */ function _moveReleasedBalance(address _account) internal virtual{ uint256 releasedToMove = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount); m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1]; m_lockedBalances[_account].pop(); } } m_balances[_account] = m_balances[_account].add(releasedToMove); } /** * Allowance related functinons */ /** * @dev Retrieve the spending allowance for a token holder by a specified account * @param _owner Token account holder * @param _spender Account given allowance * @return uint256 allowance value */ function allowance(address _owner, address _spender) public override virtual view returns (uint256) { return m_allowances[_owner][_spender]; } /** * @dev Message sender approval to spend for a specified amount * @param _spender address of party approved to spend * @param _value amount of the approval * @return boolean success status * public wrapper for _approve, _owner is msg.sender */ function approve(address _spender, uint256 _value) public override returns (bool) { bool success = _approveUNN(_msgSender(), _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: APPROVE ERROR"); } return success; } /** * @dev Token owner approval of amount for specified spender * @param _owner address of party that owns the tokens being granted approval for spending * @param _spender address of party that is granted approval for spending * @param _value amount approved for spending * @return boolean approval status * if _spender allownace for a given _owner is greater than 0, * increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738 */ function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (m_allowances[_owner][_spender] == 0 || _value == 0) ){ m_allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); retval = true; } return retval; } /** * @dev Increase spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _addedValue specified incremental increase * @return boolean increaseAllowance status * public wrapper for _increaseAllowance, _owner restricted to msg.sender */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to increase spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _addedValue specified incremental increase * @return boolean return value status * increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address. */ function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _addedValue > 0 ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * @dev Decrease spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _subtractedValue specified incremental decrease * @return boolean success status * public wrapper for _decreaseAllowance, _owner restricted to msg.sender */ //public wrapper for _decreaseAllowance, _owner restricted to msg.sender function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue); if(!success && b_revert){ revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to decrease spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _subtractedValue specified incremental decrease * @return boolean return value status * decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address. */ function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _subtractedValue > 0 && m_allowances[_owner][_spender] >= _subtractedValue ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * LockedDestination related functions */ /** * @dev Adds address as a designated destination for tokens when locked for allocation only * @param _address Address of approved desitnation for movement during lock * @return success in setting address as eligible for transfer independent of token lock status */ function setAsEligibleLockedDestination(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ m_lockedDestinations[_address] = true; retVal = true; } return retVal; } /** * @dev removes desitnation as eligible for transfer * @param _address address being removed */ function removeEligibleLockedDestination(address _address) public { if(hasRole(ROLE_ADMIN, _msgSender())){ require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); delete(m_lockedDestinations[_address]); } } /** * @dev checks whether a destination is eligible as recipient of transfer independent of token lock status * @param _address address being checked * @return whether desitnation is locked */ function checkEligibleLockedDesination(address _address) public view returns (bool) { return m_lockedDestinations[_address]; } /** * @dev Adds address as a designated allocator that can move tokens when they are locked * @param _address Address receiving the role of ROLE_ALLOCATE * @return success as true or false */ function setAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ grantRole(ROLE_ALLOCATE, _address); retVal = true; } return retVal; } /** * @dev Removes address as a designated allocator that can move tokens when they are locked * @param _address Address being removed from the ROLE_ALLOCATE * @return success as true or false */ function removeAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ if(hasRole(ROLE_ALLOCATE, _address)){ revokeRole(ROLE_ALLOCATE, _address); retVal = true; } } return retVal; } /** * @dev Checks to see if an address has the role of being an allocator * @param _address Address being checked for ROLE_ALLOCATE * @return true or false whether the address has ROLE_ALLOCATE assigned */ function checkAsAllocator(address _address) public view returns (bool) { return hasRole(ROLE_ALLOCATE, _address); } /** * Transfer related functions */ /** * @dev Public wrapper for transfer function to move tokens of specified value to a given address * @param _to specified recipient * @param _value amount being transfered to recipient * @return status of transfer success */ function transfer(address _to, uint256 _value) external override returns (bool) { bool success = _transferUNN(_msgSender(), _to, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER"); } return success; } /** * @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required. * @param _owner The address owner where transfer originates * @param _to The address to transfer to * @param _value The amount to be transferred * @return status of transfer success */ function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_to] = m_balances[_to].add(_value); retval = true; //need to move voting delegates with transfer of tokens retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value to a given address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){ bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); retval = true; //need to move voting delegates with transfer of tokens // retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferFrom function * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; } /** * @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) { if( _spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_spender] = m_balances[_spender].add(_value); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer retval = retval && _moveVotingDelegates(_owner, _spender, _value); emit Transfer(_owner, _spender, _value); } } return retval; } /** * @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer // retval = retval && _moveVotingDelegates(_owner, _to, _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public function to burn tokens * @param _value number of tokens to be burned * @return whether tokens were burned * Only ROLE_MINTER may burn tokens */ function burn(uint256 _value) external returns (bool) { bool success = _burn(_value); if(!success && b_revert){ revert("UPGT_ERROR: FAILED TO BURN"); } return success; } /** * @dev Private function Burn tokens * @param _value number of tokens to be burned * @return bool whether the tokens were burned * only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet. */ function _burn(uint256 _value) internal returns (bool) { bool retval = false; if(hasRole(ROLE_MINT, _msgSender()) && (m_balances[_msgSender()] >= _value) ){ m_balances[_msgSender()] -= _value; uint256_totalSupply = uint256_totalSupply.sub(_value); retval = true; emit Burn(_msgSender(), _value); } return retval; } /** * Voting related functions */ /** * @dev Public wrapper for _calculateVotingPower function which calulates voting power * @dev voting power = balance + locked votable balance + delegations * @return uint256 voting power */ function calculateVotingPower() public view returns (uint256) { return _calculateVotingPower(_msgSender()); } /** * @dev Calulates voting power of specified address * @param _account address of token holder * @return uint256 voting power */ function _calculateVotingPower(address _account) private view returns (uint256) { uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account)); for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) { if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){ address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i); votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount)); } } return votingPower; } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful * Requires ROLE_TEST */ function moveVotingDelegates( address _source, address _destination, uint256 _amount) public returns (bool) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _moveVotingDelegates(_source, _destination, _amount); } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful */ function _moveVotingDelegates( address _source, address _destination, uint256 _amount ) internal returns (bool) { if(_source != _destination && _amount > 0) { if(_source != BURN_ADDRESS) { uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source]; uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0; if(sourceNumberOfVotingCheckpointsOriginal >= _amount) { uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount); _writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew); } } if(_destination != BURN_ADDRESS) { uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination]; uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0; uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount); _writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew); } } return true; } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Public function for writing voting checkpoint * Requires ROLE_TEST */ function writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) public { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); _writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes); } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Private function for writing voting checkpoint */ function _writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) internal { if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes; } else { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes); _numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1); } emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes); } /** * @dev Calculate account votes as of a specific block * @param _account address whose votes are counted * @param _blockNumber from which votes are being counted * @return number of votes counted */ function getVoteCountAtBlock( address _account, uint256 _blockNumber) public view returns (uint256) { uint256 voteCount = 0; if(_blockNumber < block.number) { if(m_accountVotingCheckpoints[_account] != 0) { if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) { voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes; } else if(m_votingCheckpoints[_account][0].from > _blockNumber) { voteCount = 0; } else { uint256 lower = 0; uint256 upper = m_accountVotingCheckpoints[_account].sub(1); while(upper > lower) { uint256 center = upper.sub((upper.sub(lower).div(2))); VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center]; if(votingCheckpoint.from == _blockNumber) { voteCount = votingCheckpoint.votes; break; } else if(votingCheckpoint.from < _blockNumber) { lower = center; } else { upper = center.sub(1); } } } } } return voteCount; } /** * @dev Vote Delegation Functions * @param _to address where message sender is assigning votes * @return success of message sender delegating vote * delegate function does not allow assignment to burn */ function delegateVote(address _to) public returns (bool) { return _delegateVote(_msgSender(), _to); } /** * @dev Delegate votes from token holder to another address * @param _from Token holder * @param _toDelegate Address that will be delegated to for purpose of voting * @return success as to whether delegation has been a success */ function _delegateVote( address _from, address _toDelegate) internal returns (bool) { bool retval = false; if(_toDelegate != BURN_ADDRESS) { address currentDelegate = m_delegatedAccounts[_from]; uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from)); address oldToDelegate = m_delegatedAccounts[_from]; m_delegatedAccounts[_from] = _toDelegate; m_delegatedAccountsInverseMap[oldToDelegate].remove(_from); if(_from != _toDelegate){ m_delegatedAccountsInverseMap[_toDelegate].add(_from); } retval = true; retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance); if(retval) { if(_from == _toDelegate){ emit VotingDelegateRemoved(_from); } else{ emit VotingDelegateChanged(_from, currentDelegate, _toDelegate); } } } return retval; } /** * @dev Revert voting delegate control to owner account * @param _account The account that has delegated its vote * @return success of reverting delegation to owner */ function _revertVotingDelegationToOwner(address _account) internal returns (bool) { return _delegateVote(_account, _account); } /** * @dev Used by an message sending account to recall its voting delegates * @return success of reverting delegation to owner */ function recallVotingDelegate() public returns (bool) { return _revertVotingDelegationToOwner(_msgSender()); } /** * @dev Retrieve the voting delegate for a specified account * @param _account The account that has delegated its vote */ function getVotingDelegate(address _account) public view returns (address) { return m_delegatedAccounts[_account]; } /** * EIP-712 related functions */ /** * @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit * @param _owner address of token owner * @param _spender address of designated spender * @param _value value permitted for spend * @param _deadline expiration of signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline)) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _approveUNN(_owner, _spender, _value); } /** * @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote * @param _owner address of token owner * @param _delegate address of voting delegate * @param _expiretimestamp expiration of delegation signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @ @return bool true or false depedening on whether vote was successfully delegated */ function delegateVoteBySignature( address _owner, address _delegate, uint256 _expiretimestamp, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, _hash(VotingDelegate( { owner : _owner, delegate : _delegate, nonce : m_nonces[_owner]++, expirationTime : _expiretimestamp }) ) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _delegateVote(_owner, _delegate); } /** * @dev Public hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain * Requires ROLE_TEST */ function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_eip712Domain); } /** * @dev Hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate * Requires ROLE_TEST */ function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_delegate); } /** * @dev Public hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit * Requires ROLE_TEST */ function hashPermit(Permit memory _permit) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_permit); } /** * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function * Requires ROLE_TEST */ function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _recoverSigner(_digest, _ecv, _ecr, _ecs); } /** * @dev Private hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain */ function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(_eip712Domain.name)), keccak256(bytes(_eip712Domain.version)), _eip712Domain.chainId, _eip712Domain.verifyingContract, _eip712Domain.salt ) ); } /** * @dev Private hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate */ function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) { return keccak256( abi.encode( DELEGATE_TYPEHASH, _delegate.owner, _delegate.delegate, _delegate.nonce, _delegate.expirationTime ) ); } /** * @dev Private hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit */ function _hash(Permit memory _permit) internal pure returns (bytes32) { return keccak256(abi.encode( PERMIT_TYPEHASH, _permit.owner, _permit.spender, _permit.value, _permit.nonce, _permit.deadline )); } /** * @dev Recover signer information from provided digest * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function */ function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) { // 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(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(_digest, _ecv, _ecr, _ecs); require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../Interfaces/EIP20Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeEIP20 * @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. * This is a forked version of Openzeppelin's SafeERC20 contract but supporting * EIP20Interface instead of Openzeppelin's IERC20 * 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 SafeEIP20 { using SafeMath for uint256; using Address for address; function safeTransfer(EIP20Interface token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./MoartrollerInterface.sol"; pragma solidity ^0.6.12; interface LiquidationModelInterface { function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); struct LiquidateCalculateSeizeUserTokensArgumentsSet { PriceOracle oracle; MoartrollerInterface moartroller; address mTokenBorrowed; address mTokenCollateral; uint actualRepayAmount; address accountForLiquidation; uint liquidationIncentiveMantissa; } } // 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: BSD-3-Clause pragma solidity ^0.6.12; /** * @title MOAR's InterestRateModel Interface * @author MOAR */ interface InterestRateModelInterface { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.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; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[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(ERC721Upgradeable.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 Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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( IERC721ReceiverUpgradeable(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(ERC721Upgradeable.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 { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // 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; /** * @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.12; interface CopMappingInterface { function getTokenAddress() external view returns (address); function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint); function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address); function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256); function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint); function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint); } // 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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 "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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 IERC721ReceiverUpgradeable { /** * @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.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // 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 SafeMathUpgradeable { /** * @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; /** * @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; /** * @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 EnumerableSetUpgradeable { // 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 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 EnumerableMapUpgradeable { // 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 String operations. */ library StringsUpgradeable { /** * @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); } } // 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 IERC165Upgradeable { /** * @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.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @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, 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 { 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 `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 {_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. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _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()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // 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); } /** * @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: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/MErc20Interface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MErc20 Contract * @notice MTokens which wrap an EIP-20 underlying */ contract MErc20 is MToken, MErc20Interface { using SafeEIP20 for EIP20Interface; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function init(address underlying_, Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // MToken initialize does the bulk of the work super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems mTokens 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 uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) { return borrowForInternal(borrower, borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower. * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param mTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral); return err; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20Interface token) override external { require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. *` * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20Interface token = EIP20Interface(underlying); uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); // Calculate the amount that was *actually* transferred uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { EIP20Interface token = EIP20Interface(underlying); token.safeTransfer(to, amount); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface MErc20Interface { /*** User contract ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function borrowFor(address payable borrower, uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); }
* @dev Recover signer information from provided digest @param _digest signed, hashed message @param _ecv ECDSA v parameter @param _ecr ECDSA r parameter @param _ecs ECDSA s parameter @return address of the validated signer based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function/ 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.
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) { if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; }
11,818,620
[ 1, 27622, 10363, 1779, 628, 2112, 5403, 225, 389, 10171, 6726, 16, 14242, 883, 225, 389, 557, 90, 7773, 19748, 331, 1569, 225, 389, 557, 86, 7773, 19748, 436, 1569, 225, 389, 557, 87, 7773, 19748, 272, 1569, 327, 1758, 434, 326, 10266, 10363, 2511, 603, 1696, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 22784, 15669, 19, 7228, 19748, 18, 18281, 5910, 1435, 445, 19, 512, 2579, 17, 22, 4859, 5360, 3372, 312, 22534, 2967, 364, 425, 1793, 3165, 7675, 3581, 333, 25547, 471, 1221, 326, 3372, 3089, 18, 6181, 697, 478, 316, 326, 512, 18664, 379, 1624, 11394, 15181, 261, 4528, 30, 546, 822, 379, 18, 6662, 18, 1594, 19, 19227, 27400, 19, 27400, 18, 7699, 3631, 11164, 326, 923, 1048, 364, 272, 316, 261, 6030, 21, 4672, 374, 411, 272, 411, 1428, 84, 5034, 79, 21, 82, 225, 132, 120, 576, 397, 404, 16, 471, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 389, 266, 3165, 15647, 12, 3890, 1578, 389, 10171, 16, 2254, 28, 389, 557, 90, 16, 1731, 1578, 389, 557, 86, 16, 1731, 1578, 389, 557, 87, 13, 2713, 16618, 1135, 261, 2867, 13, 288, 203, 1377, 309, 12, 11890, 5034, 24899, 557, 87, 13, 405, 374, 92, 27, 8998, 8998, 8998, 8998, 8998, 8998, 18343, 42, 25, 40, 25, 6669, 41, 27, 4763, 27, 37, 7950, 1611, 40, 4577, 41, 9975, 42, 24, 6028, 11861, 38, 3462, 37, 20, 13, 288, 203, 1850, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 87, 11, 460, 8863, 203, 1377, 289, 203, 203, 1377, 309, 24899, 557, 90, 480, 12732, 597, 389, 557, 90, 480, 9131, 13, 288, 203, 1850, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 90, 11, 460, 8863, 203, 1377, 289, 203, 203, 1377, 2583, 12, 2977, 264, 480, 605, 8521, 67, 15140, 16, 315, 7228, 19748, 30, 2057, 3372, 8863, 203, 203, 1377, 327, 10363, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { AdministrateeInterface } from '@uma/core/contracts/oracle/interfaces/AdministrateeInterface.sol'; import { StoreInterface } from '@uma/core/contracts/oracle/interfaces/StoreInterface.sol'; import { FinderInterface } from '@uma/core/contracts/oracle/interfaces/FinderInterface.sol'; import { OracleInterfaces } from '@uma/core/contracts/oracle/implementation/Constants.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import {FeePayerPartyLib} from './FeePayerPartyLib.sol'; import {Testable} from '@uma/core/contracts/common/implementation/Testable.sol'; import {Lockable} from '@uma/core/contracts/common/implementation/Lockable.sol'; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the PerpetualParty contracts. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayerParty is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FeePayerPartyLib for FixedPoint.Unsigned; using FeePayerPartyLib for FeePayerData; using SafeERC20 for IERC20; struct FeePayerData { // The collateral currency used to back the positions in this contract. IERC20 collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface finder; // Tracks the last block time when the fees were paid. uint256 lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned cumulativeFeeMultiplier; } //---------------------------------------- // Storage //---------------------------------------- FeePayerData public feePayerData; //---------------------------------------- // Events //---------------------------------------- event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); //---------------------------------------- // Modifiers //---------------------------------------- // modifier that calls payRegularFees(). modifier fees { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } modifier onlyThisContract { require(msg.sender == address(this), 'Caller is not this contract'); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Constructs FeePayerParty contract. Called by child contracts * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) Testable(_timerAddress) { feePayerData.collateralCurrency = IERC20(_collateralAddress); feePayerData.finder = FinderInterface(_finderAddress); feePayerData.lastPaymentTime = getCurrentTime(); feePayerData.cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee * @param payer The address that pays the fees * @param amount Amount of fees to be paid */ function payFinalFees(address payer, FixedPoint.Unsigned memory amount) external onlyThisContract { _payFinalFees(payer, amount); } /** * @notice Gets the collateral currency of the derivative * @return Collateral currency */ function collateralCurrency() public view virtual nonReentrantView() returns (IERC20) { return feePayerData.collateralCurrency; } /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); totalPaid = feePayerData.payRegularFees(store, time, collateralPool); return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } //---------------------------------------- // Internal functions //---------------------------------------- // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { StoreInterface store = _getStore(); feePayerData.payFinalFees(store, payer, amount); } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); // Get Store Contract to which fees will be paid function _getStore() internal view returns (StoreInterface) { return StoreInterface( feePayerData.finder.getImplementationAddress(OracleInterfaces.Store) ); } // Calculate final fees to be paid function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(feePayerData.collateralCurrency)); } }
* @notice Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee @param payer The address that pays the fees @param amount Amount of fees to be paid/
function payFinalFees(address payer, FixedPoint.Unsigned memory amount) external onlyThisContract { _payFinalFees(payer, amount); }
908,758
[ 1, 26744, 587, 5535, 28544, 727, 1656, 281, 434, 1375, 8949, 68, 316, 1375, 12910, 2045, 287, 7623, 68, 358, 326, 4994, 6835, 18, 16269, 14036, 353, 279, 3569, 14036, 225, 293, 1773, 1021, 1758, 716, 293, 8271, 326, 1656, 281, 225, 3844, 16811, 434, 1656, 281, 358, 506, 30591, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8843, 7951, 2954, 281, 12, 2867, 293, 1773, 16, 15038, 2148, 18, 13290, 3778, 3844, 13, 203, 565, 3903, 203, 565, 1338, 2503, 8924, 203, 225, 288, 203, 565, 389, 10239, 7951, 2954, 281, 12, 84, 1773, 16, 3844, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol
Checkpoints to keep track on the evolution of each contributor vs. each garden Sub-mapping of contributor details, updated info after beta will be only at position [0]
struct ContributorPerGarden { mapping(uint256 => TimestampContribution) tsContributions; }
3,050,039
[ 1, 1564, 4139, 358, 3455, 3298, 603, 326, 2113, 5889, 434, 1517, 31123, 6195, 18, 1517, 314, 24466, 2592, 17, 6770, 434, 31123, 3189, 16, 3526, 1123, 1839, 6796, 903, 506, 1338, 622, 1754, 306, 20, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 735, 19293, 2173, 43, 24466, 288, 203, 3639, 2874, 12, 11890, 5034, 516, 8159, 442, 4027, 13, 3742, 442, 15326, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x80D2fD69467dfAB82e09D26860D5FD81CB65075E/sources/Bank.sol
TODO: Add state here
contract Bank { IERC20 usdx = IERC20(0x21d921De3BCE98D05455Fe932f060Fa6988Bb982); mapping (address => uint256) public _balance; constructor() public {} function deposit(uint amount) public { usdx.transferFrom(msg.sender, address(this), amount); _balance[msg.sender] += amount; } function withdraw(uint amount) public { uint extra_amount = amount / 10; uint total_amount = amount + extra_amount; require(_balance[msg.sender] >= amount, 'you don\'t have enoung money'); _balance[msg.sender] -= amount; usdx.transfer(msg.sender, total_amount); } }
9,574,527
[ 1, 6241, 30, 1436, 919, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 25610, 288, 203, 565, 467, 654, 39, 3462, 584, 13437, 273, 467, 654, 39, 3462, 12, 20, 92, 5340, 72, 29, 5340, 758, 23, 38, 1441, 10689, 40, 6260, 24, 2539, 2954, 29, 1578, 74, 20, 4848, 29634, 8148, 5482, 38, 70, 10689, 22, 1769, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 389, 12296, 31, 203, 377, 203, 377, 203, 565, 3885, 1435, 1071, 2618, 203, 565, 445, 443, 1724, 12, 11890, 3844, 13, 1071, 288, 203, 3639, 584, 13437, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 389, 12296, 63, 3576, 18, 15330, 65, 1011, 3844, 31, 203, 565, 289, 203, 377, 203, 565, 445, 598, 9446, 12, 11890, 3844, 13, 1071, 288, 203, 3639, 2254, 2870, 67, 8949, 273, 3844, 342, 1728, 31, 203, 3639, 2254, 2078, 67, 8949, 273, 3844, 397, 2870, 67, 8949, 31, 203, 3639, 2583, 24899, 12296, 63, 3576, 18, 15330, 65, 1545, 3844, 16, 296, 19940, 2727, 3730, 88, 1240, 570, 465, 75, 15601, 8284, 203, 3639, 389, 12296, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 3639, 584, 13437, 18, 13866, 12, 3576, 18, 15330, 16, 2078, 67, 8949, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/solady/src/utils/LibString.sol
´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ CUSTOM ERRORS */.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ @dev The `length` of the output is too small to contain all the hex digits.´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ CONSTANTS */.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ @dev The constant returned when the `search` is not found in the string.´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ DECIMAL OPERATIONS */.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ @dev Returns the base 10 decimal representation of `value`. @solidity memory-safe-assembly The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. We will need 1 word for the trailing zeros padding, 1 word for the length, and 3 words for a maximum of 78 digits. Update the free memory pointer to allocate. Zeroize the slot after the string. Cache the end of the memory to calculate the length later. We write the string from rightmost digit to leftmost digit. The following is essentially a do-while loop that also handles the zero case. Write the character to the pointer. The ASCII index of the '0' character is 48. Keep dividing `temp` until zero.
function toString(uint256 value) internal pure returns (string memory str) { assembly { str := add(mload(0x40), 0x80) mstore(0x40, add(str, 0x20)) mstore(str, 0) let end := str mstore8(str, add(48, mod(temp, 10))) temp := div(temp, 10) } let length := sub(end, str) }
840,037
[ 1, 131, 117, 30, 131, 113, 163, 227, 100, 18, 131, 113, 15, 18, 163, 227, 100, 131, 117, 29710, 140, 253, 18, 131, 113, 18, 140, 253, 163, 227, 100, 131, 117, 18, 131, 113, 30, 131, 113, 163, 227, 100, 18, 131, 113, 163, 227, 100, 18, 163, 227, 100, 131, 117, 29710, 140, 253, 18, 131, 113, 18, 140, 253, 163, 227, 100, 131, 117, 18, 131, 113, 30, 131, 113, 163, 227, 100, 18, 131, 113, 15, 18, 163, 227, 100, 131, 117, 18, 27824, 13491, 21012, 5475, 55, 15604, 342, 18, 163, 227, 100, 131, 113, 30, 131, 113, 18, 131, 117, 15, 140, 253, 18, 131, 113, 18, 140, 253, 13147, 131, 117, 163, 227, 100, 15591, 131, 113, 18, 163, 227, 100, 131, 113, 30, 131, 117, 18, 131, 117, 163, 227, 100, 18, 163, 227, 100, 131, 113, 18, 163, 227, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 609, 13, 288, 203, 3639, 19931, 288, 203, 5411, 609, 519, 527, 12, 81, 945, 12, 20, 92, 7132, 3631, 374, 92, 3672, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 527, 12, 701, 16, 374, 92, 3462, 3719, 203, 5411, 312, 2233, 12, 701, 16, 374, 13, 203, 203, 5411, 2231, 679, 519, 609, 203, 203, 7734, 312, 2233, 28, 12, 701, 16, 527, 12, 8875, 16, 681, 12, 5814, 16, 1728, 20349, 203, 7734, 1906, 519, 3739, 12, 5814, 16, 1728, 13, 203, 5411, 289, 203, 203, 5411, 2231, 769, 519, 720, 12, 409, 16, 609, 13, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x216B371081DDB9a7047C46a63e86647Abdf0D04E/sources/contract/Canbeat-Staking/Canbeat-Staking.sol
Fee Definition Initialize this contract's state.
constructor(address _defaultAdmin, uint256 _stakingsection, DropERC1155 _NodeNFTToken, TokenERC20 _RewardToken, address _DaoAddress, uint256 _rewardPerMin, uint256 _alreadyClaimed) { StakingSection = _stakingsection; IStakingSection = _stakingsection - 1; NodeNftCollection = _NodeNFTToken; rewardsToken = _RewardToken; DaoAddress = _DaoAddress; rewardPerMin = _rewardPerMin; DaoRoyalty = [5, 10, 15, 20]; AgentRoyalty = 2; PausePool = false; PauseClaim = false; _owner = _defaultAdmin; totalClaimed = _alreadyClaimed; _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); }
3,739,842
[ 1, 14667, 10849, 9190, 333, 6835, 1807, 919, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 1886, 4446, 16, 2254, 5034, 389, 334, 6159, 3464, 16, 10895, 654, 39, 2499, 2539, 389, 907, 50, 4464, 1345, 16, 3155, 654, 39, 3462, 389, 17631, 1060, 1345, 16, 1758, 389, 11412, 1887, 16, 2254, 5034, 389, 266, 2913, 2173, 2930, 16, 2254, 5034, 389, 17583, 9762, 329, 13, 288, 203, 3639, 934, 6159, 5285, 273, 389, 334, 6159, 3464, 31, 203, 3639, 467, 510, 6159, 5285, 273, 389, 334, 6159, 3464, 300, 404, 31, 203, 540, 203, 3639, 2029, 50, 1222, 2532, 273, 389, 907, 50, 4464, 1345, 31, 203, 3639, 283, 6397, 1345, 273, 389, 17631, 1060, 1345, 31, 203, 3639, 463, 6033, 1887, 273, 389, 11412, 1887, 31, 203, 3639, 19890, 2173, 2930, 273, 389, 266, 2913, 2173, 2930, 31, 203, 540, 203, 3639, 463, 6033, 54, 13372, 15006, 273, 306, 25, 16, 1728, 16, 4711, 16, 4200, 15533, 203, 3639, 8669, 54, 13372, 15006, 273, 576, 31, 203, 203, 3639, 31357, 2864, 273, 629, 31, 203, 3639, 31357, 9762, 273, 629, 31, 203, 3639, 389, 8443, 273, 389, 1886, 4446, 31, 203, 3639, 2078, 9762, 329, 273, 389, 17583, 9762, 329, 31, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 1886, 4446, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // SPDX-License-Identifier: MIT 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 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/utils/introspection/ERC165Storage.sol pragma solidity ^0.8.0; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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: @openzeppelin/contracts/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/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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/access/IKOAccessControlsLookup.sol pragma solidity 0.8.4; interface IKOAccessControlsLookup { function hasAdminRole(address _address) external view returns (bool); function isVerifiedArtist(uint256 _index, address _account, bytes32[] calldata _merkleProof) external view returns (bool); function isVerifiedArtistProxy(address _artist, address _proxy) external view returns (bool); function hasLegacyMinterRole(address _address) external view returns (bool); function hasContractRole(address _address) external view returns (bool); function hasContractOrAdminRole(address _address) external view returns (bool); } // File: contracts/core/IERC2981.sol pragma solidity 0.8.4; /// @notice This is purely an extension for the KO platform /// @notice Royalties on KO are defined at an edition level for all tokens from the same edition interface IERC2981EditionExtension { /// @notice Does the edition have any royalties defined function hasRoyalties(uint256 _editionId) external view returns (bool); /// @notice Get the royalty receiver - all royalties should be sent to this account if not zero address function getRoyaltiesReceiver(uint256 _editionId) external view returns (address); } /** * ERC2981 standards interface for royalties */ interface IERC2981 is IERC165, IERC2981EditionExtension { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for _value sale price function royaltyInfo( uint256 _tokenId, uint256 _value ) external view returns ( address _receiver, uint256 _royaltyAmount ); } // File: contracts/core/IKODAV3Minter.sol pragma solidity 0.8.4; interface IKODAV3Minter { function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); function mintBatchEditionAndComposeERC20s(uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts) external returns (uint256 _editionId); function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); } // File: contracts/programmable/ITokenUriResolver.sol pragma solidity 0.8.4; interface ITokenUriResolver { /// @notice Return the edition or token level URI - token level trumps edition level if found function tokenURI(uint256 _editionId, uint256 _tokenId) external view returns (string memory); /// @notice Do we have an edition level or token level token URI resolver set function isDefined(uint256 _editionId, uint256 _tokenId) external view returns (bool); } // File: @openzeppelin/contracts/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/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/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]; } // 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)); } } // File: @openzeppelin/contracts/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 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; } } // File: @openzeppelin/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) { return msg.data; } } // File: contracts/core/IERC2309.sol pragma solidity 0.8.4; /** @title ERC-2309: ERC-721 Batch Mint Extension @dev https://github.com/ethereum/EIPs/issues/2309 */ interface IERC2309 { /** @notice This event is emitted when ownership of a batch of tokens changes by any mechanism. This includes minting, transferring, and burning. @dev The address executing the transaction MUST own all the tokens within the range of fromTokenId and toTokenId, or MUST be an approved operator to act on the owners behalf. The fromTokenId and toTokenId MUST be a sequential range of tokens IDs. When minting/creating tokens, the `fromAddress` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `toAddress` argument MUST be set to `0x0` (i.e. zero address). @param fromTokenId The token ID that begins the batch of tokens being transferred @param toTokenId The token ID that ends the batch of tokens being transferred @param fromAddress The address transferring ownership of the specified range of tokens @param toAddress The address receiving ownership of the specified range of tokens. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // File: contracts/core/IHasSecondarySaleFees.sol pragma solidity 0.8.4; /// @title Royalties formats required for use on the Rarible platform /// @dev https://docs.rarible.com/asset/royalties-schema interface IHasSecondarySaleFees is IERC165 { event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); function getFeeRecipients(uint256 id) external returns (address payable[] memory); function getFeeBps(uint256 id) external returns (uint[] memory); } // File: contracts/core/IKODAV3.sol pragma solidity 0.8.4; /// @title Core KODA V3 functionality interface IKODAV3 is IERC165, // Contract introspection IERC721, // Core NFTs IERC2309, // Consecutive batch mint IERC2981, // Royalties IHasSecondarySaleFees // Rariable / Foundation royalties { // edition utils function getCreatorOfEdition(uint256 _editionId) external view returns (address _originalCreator); function getCreatorOfToken(uint256 _tokenId) external view returns (address _originalCreator); function getSizeOfEdition(uint256 _editionId) external view returns (uint256 _size); function getEditionSizeOfToken(uint256 _tokenId) external view returns (uint256 _size); function editionExists(uint256 _editionId) external view returns (bool); // Has the edition been disabled / soft burnt function isEditionSalesDisabled(uint256 _editionId) external view returns (bool); // Has the edition been disabled / soft burnt OR sold out function isSalesDisabledOrSoldOut(uint256 _editionId) external view returns (bool); // Work out the max token ID for an edition ID function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId); // Helper method for getting the next primary sale token from an edition starting low to high token IDs function getNextAvailablePrimarySaleToken(uint256 _editionId) external returns (uint256 _tokenId); // Helper method for getting the next primary sale token from an edition starting high to low token IDs function getReverseAvailablePrimarySaleToken(uint256 _editionId) external view returns (uint256 _tokenId); // Utility method to get all data needed for the next primary sale, low token ID to high function facilitateNextPrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId); // Utility method to get all data needed for the next primary sale, high token ID to low function facilitateReversePrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId); // Expanded royalty method for the edition, not token function royaltyAndCreatorInfo(uint256 _editionId, uint256 _value) external returns (address _receiver, address _creator, uint256 _amount); // Allows the creator to correct mistakes until the first token from an edition is sold function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external; // Has any primary transfer happened from an edition function hasMadePrimarySale(uint256 _editionId) external view returns (bool); // Has the edition sold out function isEditionSoldOut(uint256 _editionId) external view returns (bool); // Toggle on/off the edition from being able to make sales function toggleEditionSalesDisabled(uint256 _editionId) external; // token utils function exists(uint256 _tokenId) external view returns (bool); function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId); function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri); function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool); } // File: contracts/core/composable/TopDownERC20Composable.sol pragma solidity 0.8.4; interface ERC998ERC20TopDown { event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value); event ReceivedERC20ForEdition(address indexed _from, uint256 indexed _editionId, address indexed _erc20Contract, uint256 _value); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value); function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256); function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external; function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) external; } interface ERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } /// @notice ERC998 ERC721 > ERC20 Top Down implementation abstract contract TopDownERC20Composable is ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, ReentrancyGuard, Context { using EnumerableSet for EnumerableSet.AddressSet; // Edition ID -> ERC20 contract -> Balance of ERC20 for every token in Edition mapping(uint256 => mapping(address => uint256)) public editionTokenERC20Balances; // Edition ID -> ERC20 contract -> Token ID -> Balance Transferred out of token mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public editionTokenERC20TransferAmounts; // Edition ID -> Linked ERC20 contract addresses mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInEdition; // Token ID -> Linked ERC20 contract addresses mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInNft; // Token ID -> ERC20 contract -> balance of ERC20 owned by token mapping(uint256 => mapping(address => uint256)) public ERC20Balances; /// @notice the ERC20 balance of a NFT token given an ERC20 token address function balanceOfERC20(uint256 _tokenId, address _erc20Contract) public override view returns (uint256) { IKODAV3 koda = IKODAV3(address(this)); uint256 editionId = koda.getEditionIdOfToken(_tokenId); uint256 editionBalance = editionTokenERC20Balances[editionId][_erc20Contract]; uint256 tokenEditionBalance = editionBalance / koda.getSizeOfEdition(editionId); uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId]; tokenEditionBalance = tokenEditionBalance - spentTokens; return tokenEditionBalance + ERC20Balances[_tokenId][_erc20Contract]; } /// @notice Transfer out an ERC20 from an NFT function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external override nonReentrant { _prepareERC20LikeTransfer(_tokenId, _to, _erc20Contract, _value); IERC20(_erc20Contract).transfer(_to, _value); emit TransferERC20(_tokenId, _to, _erc20Contract, _value); } /// @notice An NFT token owner (or approved) can compose multiple ERC20s in their NFT function getERC20s(address _from, uint256[] calldata _tokenIds, address _erc20Contract, uint256 _totalValue) external { uint256 totalTokens = _tokenIds.length; require(totalTokens > 0 && _totalValue > 0, "Empty values"); uint256 valuePerToken = _totalValue / totalTokens; for (uint i = 0; i < totalTokens; i++) { getERC20(_from, _tokenIds[i], _erc20Contract, valuePerToken); } } /// @notice A NFT token owner (or approved address) can compose any ERC20 in their NFT function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) public override nonReentrant { require(_value > 0, "Value zero"); require(_from == _msgSender(), "Only owner"); address spender = _msgSender(); IERC721 self = IERC721(address(this)); address owner = self.ownerOf(_tokenId); require( owner == spender || self.isApprovedForAll(owner, spender) || self.getApproved(_tokenId) == spender, "Invalid spender" ); uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); bool editionAlreadyContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract); bool nftAlreadyContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract); // does not already contain _erc20Contract if (!editionAlreadyContainsERC20 && !nftAlreadyContainsERC20) { ERC20sEmbeddedInNft[_tokenId].add(_erc20Contract); } ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] + _value; IERC20 token = IERC20(_erc20Contract); require(token.allowance(_from, address(this)) >= _value, "Exceeds allowance"); token.transferFrom(_from, address(this), _value); emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value); } function _composeERC20IntoEdition(address _from, uint256 _editionId, address _erc20Contract, uint256 _value) internal nonReentrant { require(_value > 0, "Value zero"); require(!ERC20sEmbeddedInEdition[_editionId].contains(_erc20Contract), "Edition contains ERC20"); ERC20sEmbeddedInEdition[_editionId].add(_erc20Contract); editionTokenERC20Balances[_editionId][_erc20Contract] = editionTokenERC20Balances[_editionId][_erc20Contract] + _value; IERC20(_erc20Contract).transferFrom(_from, address(this), _value); emit ReceivedERC20ForEdition(_from, _editionId, _erc20Contract, _value); } function totalERC20Contracts(uint256 _tokenId) override public view returns (uint256) { uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); return ERC20sEmbeddedInNft[_tokenId].length() + ERC20sEmbeddedInEdition[editionId].length(); } function erc20ContractByIndex(uint256 _tokenId, uint256 _index) override external view returns (address) { uint256 numOfERC20sInNFT = ERC20sEmbeddedInNft[_tokenId].length(); if (_index >= numOfERC20sInNFT) { uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); return ERC20sEmbeddedInEdition[editionId].at(_index - numOfERC20sInNFT); } return ERC20sEmbeddedInNft[_tokenId].at(_index); } /// --- Internal ---- function _prepareERC20LikeTransfer(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) private { // To avoid stack too deep, do input checks within this scope { require(_value > 0, "Value zero"); require(_to != address(0), "Zero address"); IERC721 self = IERC721(address(this)); address owner = self.ownerOf(_tokenId); require( owner == _msgSender() || self.isApprovedForAll(owner, _msgSender()) || self.getApproved(_tokenId) == _msgSender(), "Not owner" ); } // Check that the NFT contains the ERC20 bool nftContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract); IKODAV3 koda = IKODAV3(address(this)); uint256 editionId = koda.getEditionIdOfToken(_tokenId); bool editionContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract); require(nftContainsERC20 || editionContainsERC20, "No such ERC20"); // Check there is enough balance to transfer out require(balanceOfERC20(_tokenId, _erc20Contract) >= _value, "Exceeds balance"); uint256 editionSize = koda.getSizeOfEdition(editionId); uint256 tokenInitialBalance = editionTokenERC20Balances[editionId][_erc20Contract] / editionSize; uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId]; uint256 editionTokenBalance = tokenInitialBalance - spentTokens; // Check whether the value can be fully transferred from the edition balance, token balance or both balances if (editionTokenBalance >= _value) { editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + _value; } else if (ERC20Balances[_tokenId][_erc20Contract] >= _value) { ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - _value; } else { // take from both balances editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + editionTokenBalance; uint256 amountOfTokensToSpendFromTokenBalance = _value - editionTokenBalance; ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - amountOfTokensToSpendFromTokenBalance; } // The ERC20 is no longer composed within the token if the balance falls to zero if (nftContainsERC20 && ERC20Balances[_tokenId][_erc20Contract] == 0) { ERC20sEmbeddedInNft[_tokenId].remove(_erc20Contract); } // If all tokens in an edition have spent their ERC20 balance, then we can remove the link if (editionContainsERC20) { uint256 allTokensInEditionERC20Balance; for (uint i = 0; i < editionSize; i++) { uint256 tokenBal = tokenInitialBalance - editionTokenERC20TransferAmounts[editionId][_erc20Contract][editionId + i]; allTokensInEditionERC20Balance = allTokensInEditionERC20Balance + tokenBal; } if (allTokensInEditionERC20Balance == 0) { ERC20sEmbeddedInEdition[editionId].remove(_erc20Contract); } } } } // File: contracts/core/composable/TopDownSimpleERC721Composable.sol pragma solidity 0.8.4; abstract contract TopDownSimpleERC721Composable is Context { struct ComposedNFT { address nft; uint256 tokenId; } // KODA Token ID -> composed nft mapping(uint256 => ComposedNFT) public kodaTokenComposedNFT; // External NFT address -> External Token ID -> KODA token ID mapping(address => mapping(uint256 => uint256)) public composedNFTsToKodaToken; event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId); event TransferChild(uint256 indexed _tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId); /// @notice compose a set of the same child ERC721s into a KODA tokens /// @notice Caller must own both KODA and child NFT tokens function composeNFTsIntoKodaTokens(uint256[] calldata _kodaTokenIds, address _nft, uint256[] calldata _nftTokenIds) external { uint256 totalKodaTokens = _kodaTokenIds.length; require(totalKodaTokens > 0 && totalKodaTokens == _nftTokenIds.length, "Invalid list"); IERC721 nftContract = IERC721(_nft); for (uint i = 0; i < totalKodaTokens; i++) { uint256 _kodaTokenId = _kodaTokenIds[i]; uint256 _nftTokenId = _nftTokenIds[i]; require( IERC721(address(this)).ownerOf(_kodaTokenId) == nftContract.ownerOf(_nftTokenId), "Owner mismatch" ); kodaTokenComposedNFT[_kodaTokenId] = ComposedNFT(_nft, _nftTokenId); composedNFTsToKodaToken[_nft][_nftTokenId] = _kodaTokenId; nftContract.transferFrom(_msgSender(), address(this), _nftTokenId); emit ReceivedChild(_msgSender(), _kodaTokenId, _nft, _nftTokenId); } } /// @notice Transfer a child 721 wrapped within a KODA token to a given recipient /// @notice only KODA token owner can call this function transferChild(uint256 _kodaTokenId, address _recipient) external { require( IERC721(address(this)).ownerOf(_kodaTokenId) == _msgSender(), "Only KODA owner" ); address nft = kodaTokenComposedNFT[_kodaTokenId].nft; uint256 nftId = kodaTokenComposedNFT[_kodaTokenId].tokenId; delete kodaTokenComposedNFT[_kodaTokenId]; delete composedNFTsToKodaToken[nft][nftId]; IERC721(nft).transferFrom(address(this), _recipient, nftId); emit TransferChild(_kodaTokenId, _recipient, nft, nftId); } } // File: contracts/core/Konstants.sol pragma solidity 0.8.4; contract Konstants { // Every edition always goes up in batches of 1000 uint16 public constant MAX_EDITION_SIZE = 1000; // magic method that defines the maximum range for an edition - this is fixed forever - tokens are minted in range function _editionFromTokenId(uint256 _tokenId) internal pure returns (uint256) { return (_tokenId / MAX_EDITION_SIZE) * MAX_EDITION_SIZE; } } // File: contracts/core/BaseKoda.sol pragma solidity 0.8.4; abstract contract BaseKoda is Konstants, Context, IKODAV3 { bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); event AdminUpdateSecondaryRoyalty(uint256 _secondarySaleRoyalty); event AdminUpdateBasisPointsModulo(uint256 _basisPointsModulo); event AdminUpdateModulo(uint256 _modulo); event AdminEditionReported(uint256 indexed _editionId, bool indexed _reported); event AdminArtistAccountReported(address indexed _account, bool indexed _reported); event AdminUpdateAccessControls(IKOAccessControlsLookup indexed _oldAddress, IKOAccessControlsLookup indexed _newAddress); modifier onlyContract(){ _onlyContract(); _; } function _onlyContract() private view { require(accessControls.hasContractRole(_msgSender()), "Must be contract"); } modifier onlyAdmin(){ _onlyAdmin(); _; } function _onlyAdmin() private view { require(accessControls.hasAdminRole(_msgSender()), "Must be admin"); } IKOAccessControlsLookup public accessControls; // A onchain reference to editions which have been reported for some infringement purposes to KO mapping(uint256 => bool) public reportedEditionIds; // A onchain reference to accounts which have been lost/hacked etc mapping(address => bool) public reportedArtistAccounts; // Secondary sale commission uint256 public secondarySaleRoyalty = 12_50000; // 12.5% by default /// @notice precision 100.00000% uint256 public modulo = 100_00000; /// @notice Basis points conversion modulo /// @notice This is used by the IHasSecondarySaleFees implementation which is different than EIP-2981 specs uint256 public basisPointsModulo = 1000; constructor(IKOAccessControlsLookup _accessControls) { accessControls = _accessControls; } function reportEditionId(uint256 _editionId, bool _reported) onlyAdmin public { reportedEditionIds[_editionId] = _reported; emit AdminEditionReported(_editionId, _reported); } function reportArtistAccount(address _account, bool _reported) onlyAdmin public { reportedArtistAccounts[_account] = _reported; emit AdminArtistAccountReported(_account, _reported); } function updateBasisPointsModulo(uint256 _basisPointsModulo) onlyAdmin public { require(_basisPointsModulo > 0, "Is zero"); basisPointsModulo = _basisPointsModulo; emit AdminUpdateBasisPointsModulo(_basisPointsModulo); } function updateModulo(uint256 _modulo) onlyAdmin public { require(_modulo > 0, "Is zero"); modulo = _modulo; emit AdminUpdateModulo(_modulo); } function updateSecondaryRoyalty(uint256 _secondarySaleRoyalty) onlyAdmin public { secondarySaleRoyalty = _secondarySaleRoyalty; emit AdminUpdateSecondaryRoyalty(_secondarySaleRoyalty); } function updateAccessControls(IKOAccessControlsLookup _accessControls) public onlyAdmin { require(_accessControls.hasAdminRole(_msgSender()), "Must be admin"); emit AdminUpdateAccessControls(accessControls, _accessControls); accessControls = _accessControls; } /// @dev Allows for the ability to extract stuck ERC20 tokens /// @dev Only callable from admin function withdrawStuckTokens(address _tokenAddress, uint256 _amount, address _withdrawalAccount) onlyAdmin public { IERC20(_tokenAddress).transfer(_withdrawalAccount, _amount); } } // File: contracts/core/KnownOriginDigitalAssetV3.sol pragma solidity 0.8.4; /// @title A ERC-721 compliant contract which has a focus on being GAS efficient along with being able to support /// both unique tokens and multi-editions sharing common traits but of limited supply /// /// @author KnownOrigin Labs - https://knownorigin.io/ /// /// @notice The NFT supports a range of standards such as: /// @notice EIP-2981 Royalties Standard /// @notice EIP-2309 Consecutive batch mint /// @notice ERC-998 Top-down ERC-20 composable contract KnownOriginDigitalAssetV3 is TopDownERC20Composable, TopDownSimpleERC721Composable, BaseKoda, ERC165Storage, IKODAV3Minter { event EditionURIUpdated(uint256 indexed _editionId); event EditionSalesDisabledToggled(uint256 indexed _editionId, bool _oldValue, bool _newValue); event SealedEditionMetaDataSet(uint256 indexed _editionId); event SealedTokenMetaDataSet(uint256 indexed _tokenId); event AdditionalEditionUnlockableSet(uint256 indexed _editionId); event AdminRoyaltiesRegistryProxySet(address indexed _royaltiesRegistryProxy); event AdminTokenUriResolverSet(address indexed _tokenUriResolver); modifier validateEdition(uint256 _editionId) { _validateEdition(_editionId); _; } function _validateEdition(uint256 _editionId) private view { require(_editionExists(_editionId), "Edition does not exist"); } modifier validateCreator(uint256 _editionId) { address creator = getCreatorOfEdition(_editionId); require( _msgSender() == creator || accessControls.isVerifiedArtistProxy(creator, _msgSender()), "Only creator or proxy" ); _; } /// @notice Token name string public constant name = "KnownOriginDigitalAsset"; /// @notice Token symbol string public constant symbol = "KODA"; /// @notice KODA version string public constant version = "3"; /// @notice Royalties registry IERC2981 public royaltiesRegistryProxy; /// @notice Token URI resolver ITokenUriResolver public tokenUriResolver; /// @notice Edition number pointer uint256 public editionPointer; struct EditionDetails { address creator; // primary edition/token creator uint16 editionSize; // onchain edition size string uri; // the referenced metadata } /// @dev tokens are minted in batches - the first token ID used is representative of the edition ID mapping(uint256 => EditionDetails) internal editionDetails; /// @dev Mapping of tokenId => owner - only set on first transfer (after mint) such as a primary sale and/or gift mapping(uint256 => address) internal owners; /// @dev Mapping of owner => number of tokens owned mapping(address => uint256) internal balances; /// @dev Mapping of tokenId => approved address mapping(uint256 => address) internal approvals; /// @dev Mapping of owner => operator => approved mapping(address => mapping(address => bool)) internal operatorApprovals; /// @notice Optional one time use storage slot for additional edition metadata mapping(uint256 => string) public sealedEditionMetaData; /// @notice Optional one time use storage slot for additional token metadata such ass peramweb metadata mapping(uint256 => string) public sealedTokenMetaData; /// @notice Allows a creator to disable sales of their edition mapping(uint256 => bool) public editionSalesDisabled; constructor( IKOAccessControlsLookup _accessControls, IERC2981 _royaltiesRegistryProxy, uint256 _editionPointer ) BaseKoda(_accessControls) { // starting point for new edition IDs editionPointer = _editionPointer; // optional registry address - can be constructed as zero address royaltiesRegistryProxy = _royaltiesRegistryProxy; // INTERFACE_ID_ERC721 _registerInterface(0x80ac58cd); // INTERFACE_ID_ERC721_METADATA _registerInterface(0x5b5e139f); // _INTERFACE_ID_ERC2981 _registerInterface(0x2a55205a); // _INTERFACE_ID_FEES _registerInterface(0xb7799584); } /// @notice Mints batches of tokens emitting multiple Transfer events function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) public override onlyContract returns (uint256 _editionId) { return _mintBatchEdition(_editionSize, _to, _uri); } /// @notice Mints an edition token batch and composes ERC20s for every token in the edition function mintBatchEditionAndComposeERC20s( uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts ) external override onlyContract returns (uint256 _editionId) { uint256 totalErc20s = _erc20s.length; require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid"); _editionId = _mintBatchEdition(_editionSize, _to, _uri); for (uint i = 0; i < totalErc20s; i++) { _composeERC20IntoEdition(_to, _editionId, _erc20s[i], _amounts[i]); } } function _mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) internal returns (uint256) { require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size"); uint256 start = generateNextEditionNumber(); // N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation // assign balance balances[_to] = balances[_to] + _editionSize; // edition of x editionDetails[start] = EditionDetails(_to, _editionSize, _uri); // Loop emit all transfer events uint256 end = start + _editionSize; for (uint i = start; i < end; i++) { emit Transfer(address(0), _to, i); } return start; } /// @notice Mints batches of tokens but emits a single ConsecutiveTransfer event EIP-2309 function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) public override onlyContract returns (uint256 _editionId) { require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size"); uint256 start = generateNextEditionNumber(); // N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation // assign balance balances[_to] = balances[_to] + _editionSize; // Start ID always equals edition ID editionDetails[start] = EditionDetails(_to, _editionSize, _uri); // emit EIP-2309 consecutive transfer event emit ConsecutiveTransfer(start, start + _editionSize, address(0), _to); return start; } /// @notice Allows the creator of an edition to update the token URI provided that no primary sales have been made function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external override validateCreator(_editionId) { require( !hasMadePrimarySale(_editionId) && (!tokenUriResolverActive() || !tokenUriResolver.isDefined(_editionId, 0)), "Invalid state" ); editionDetails[_editionId].uri = _newURI; emit EditionURIUpdated(_editionId); } /// @notice Increases the edition pointer and then returns this pointer for minting methods function generateNextEditionNumber() internal returns (uint256) { editionPointer = editionPointer + MAX_EDITION_SIZE; return editionPointer; } /// @notice URI for an edition. Individual tokens in an edition will have this URI when tokenURI() is called function editionURI(uint256 _editionId) validateEdition(_editionId) public view returns (string memory) { // Here we are checking only that the edition has a edition level resolver - there may be a overridden token level resolver if (tokenUriResolverActive() && tokenUriResolver.isDefined(_editionId, 0)) { return tokenUriResolver.tokenURI(_editionId, 0); } return editionDetails[_editionId].uri; } /// @notice Returns the URI based on the edition associated with a token function tokenURI(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "Token does not exist"); uint256 editionId = _editionFromTokenId(_tokenId); if (tokenUriResolverActive() && tokenUriResolver.isDefined(editionId, _tokenId)) { return tokenUriResolver.tokenURI(editionId, _tokenId); } return editionDetails[editionId].uri; } /// @notice Allows the caller to check if external URI resolver is active function tokenUriResolverActive() public view returns (bool) { return address(tokenUriResolver) != address(0); } /// @notice Additional metadata string for an edition function editionAdditionalMetaData(uint256 _editionId) public view returns (string memory) { return sealedEditionMetaData[_editionId]; } /// @notice Additional metadata string for a token function tokenAdditionalMetaData(uint256 _tokenId) public view returns (string memory) { return sealedTokenMetaData[_tokenId]; } /// @notice Additional metadata string for an edition given a token ID function editionAdditionalMetaDataForToken(uint256 _tokenId) public view returns (string memory) { uint256 editionId = _editionFromTokenId(_tokenId); return sealedEditionMetaData[editionId]; } function getEditionDetails(uint256 _tokenId) public override view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri) { uint256 editionId = _editionFromTokenId(_tokenId); EditionDetails storage edition = editionDetails[editionId]; return ( edition.creator, _ownerOf(_tokenId, editionId), edition.editionSize, editionId, tokenURI(_tokenId) ); } /// @notice If primary sales for an edition are disabled function isEditionSalesDisabled(uint256 _editionId) external view override returns (bool) { return editionSalesDisabled[_editionId]; } /// @notice If primary sales for an edition are disabled or if the edition is sold out function isSalesDisabledOrSoldOut(uint256 _editionId) external view override returns (bool) { return editionSalesDisabled[_editionId] || isEditionSoldOut(_editionId); } /// @notice Toggle for disabling primary sales for an edition function toggleEditionSalesDisabled(uint256 _editionId) validateEdition(_editionId) external override { address creator = editionDetails[_editionId].creator; require( creator == _msgSender() || accessControls.hasAdminRole(_msgSender()), "Only creator or admin" ); emit EditionSalesDisabledToggled(_editionId, editionSalesDisabled[_editionId], !editionSalesDisabled[_editionId]); editionSalesDisabled[_editionId] = !editionSalesDisabled[_editionId]; } /////////////////// // Creator query // /////////////////// function getCreatorOfEdition(uint256 _editionId) public override view returns (address _originalCreator) { return _getCreatorOfEdition(_editionId); } function getCreatorOfToken(uint256 _tokenId) public override view returns (address _originalCreator) { return _getCreatorOfEdition(_editionFromTokenId(_tokenId)); } function _getCreatorOfEdition(uint256 _editionId) internal view returns (address _originalCreator) { return editionDetails[_editionId].creator; } //////////////// // Size query // //////////////// function getSizeOfEdition(uint256 _editionId) public override view returns (uint256 _size) { return editionDetails[_editionId].editionSize; } function getEditionSizeOfToken(uint256 _tokenId) public override view returns (uint256 _size) { return editionDetails[_editionFromTokenId(_tokenId)].editionSize; } ///////////////////// // Existence query // ///////////////////// function editionExists(uint256 _editionId) public override view returns (bool) { return _editionExists(_editionId); } function _editionExists(uint256 _editionId) internal view returns (bool) { return editionDetails[_editionId].editionSize > 0; } function exists(uint256 _tokenId) public override view returns (bool) { return _exists(_tokenId); } function _exists(uint256 _tokenId) internal view returns (bool) { return _ownerOf(_tokenId, _editionFromTokenId(_tokenId)) != address(0); } /// @notice Returns the last token ID of an edition based on the edition's size function maxTokenIdOfEdition(uint256 _editionId) public override view returns (uint256 _tokenId) { return _maxTokenIdOfEdition(_editionId); } function _maxTokenIdOfEdition(uint256 _editionId) internal view returns (uint256 _tokenId) { return editionDetails[_editionId].editionSize + _editionId; } //////////////// // Edition ID // //////////////// function getEditionIdOfToken(uint256 _tokenId) public override pure returns (uint256 _editionId) { return _editionFromTokenId(_tokenId); } function _royaltyInfo(uint256 _tokenId, uint256 _value) internal view returns (address _receiver, uint256 _royaltyAmount) { uint256 editionId = _editionFromTokenId(_tokenId); // If we have a registry and its defined, use it if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) { // Note: any registry must be edition aware so to only store one entry for all within the edition (_receiver, _royaltyAmount) = royaltiesRegistryProxy.royaltyInfo(editionId, _value); } else { // Fall back to KO defaults _receiver = _getCreatorOfEdition(editionId); _royaltyAmount = (_value / modulo) * secondarySaleRoyalty; } } ////////////// // ERC-2981 // ////////////// // Abstract away token royalty registry, proxy through to the implementation function royaltyInfo(uint256 _tokenId, uint256 _value) external override view returns (address _receiver, uint256 _royaltyAmount) { return _royaltyInfo(_tokenId, _value); } // Expanded method at edition level and expanding on the funds receiver and the creator function royaltyAndCreatorInfo(uint256 _tokenId, uint256 _value) external view override returns (address receiver, address creator, uint256 royaltyAmount) { address originalCreator = _getCreatorOfEdition(_editionFromTokenId(_tokenId)); (address _receiver, uint256 _royaltyAmount) = _royaltyInfo(_tokenId, _value); return (_receiver, originalCreator, _royaltyAmount); } function hasRoyalties(uint256 _editionId) validateEdition(_editionId) external override view returns (bool) { return royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId) || secondarySaleRoyalty > 0; } function getRoyaltiesReceiver(uint256 _tokenId) public override view returns (address) { uint256 editionId = _editionFromTokenId(_tokenId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) { return royaltiesRegistryProxy.getRoyaltiesReceiver(editionId); } return _getCreatorOfEdition(editionId); } function royaltyRegistryActive() public view returns (bool) { return address(royaltiesRegistryProxy) != address(0); } ////////////////////////////// // Has Secondary Sale Fees // //////////////////////////// function getFeeRecipients(uint256 _tokenId) external view override returns (address payable[] memory) { address payable[] memory feeRecipients = new address payable[](1); feeRecipients[0] = payable(getRoyaltiesReceiver(_tokenId)); return feeRecipients; } function getFeeBps(uint256) external view override returns (uint[] memory) { uint[] memory feeBps = new uint[](1); feeBps[0] = uint(secondarySaleRoyalty) / basisPointsModulo; // convert to basis points return feeBps; } //////////////////////////////////// // Primary Sale Utilities methods // //////////////////////////////////// /// @notice List of token IDs that are still with the original creator function getAllUnsoldTokenIdsForEdition(uint256 _editionId) validateEdition(_editionId) public view returns (uint256[] memory) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // work out number of unsold tokens in order to allocate memory to an array later uint256 numOfUnsoldTokens; for (uint256 i = _editionId; i < maxTokenId; i++) { // if no owner set - assume primary if not moved if (owners[i] == address(0)) { numOfUnsoldTokens += 1; } } uint256[] memory unsoldTokens = new uint256[](numOfUnsoldTokens); // record token IDs of unsold tokens uint256 nextIndex; for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { unsoldTokens[nextIndex] = tokenId; nextIndex += 1; } } return unsoldTokens; } /// @notice For a given edition, returns the next token and associated royalty information function facilitateNextPrimarySale(uint256 _editionId) public view override returns (address receiver, address creator, uint256 tokenId) { require(!editionSalesDisabled[_editionId], "Edition disabled"); uint256 _tokenId = getNextAvailablePrimarySaleToken(_editionId); address _creator = _getCreatorOfEdition(_editionId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) { address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId); return (_receiver, _creator, _tokenId); } return (_creator, _creator, _tokenId); } /// @notice Return the next unsold token ID for a given edition unless all tokens have been sold function getNextAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { return tokenId; } } revert("Primary market exhausted"); } /// @notice Starting from the last token in an edition and going down the first, returns the next unsold token (if any) function getReverseAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) { uint256 highestTokenId = _maxTokenIdOfEdition(_editionId) - 1; // high to low while (highestTokenId >= _editionId) { // if no owner set - assume primary if not moved if (owners[highestTokenId] == address(0)) { return highestTokenId; } highestTokenId--; } revert("Primary market exhausted"); } /// @notice Using the reverse token ID logic of an edition, returns next token ID and associated royalty information function facilitateReversePrimarySale(uint256 _editionId) public view override returns (address receiver, address creator, uint256 tokenId) { require(!editionSalesDisabled[_editionId], "Edition disabled"); uint256 _tokenId = getReverseAvailablePrimarySaleToken(_editionId); address _creator = _getCreatorOfEdition(_editionId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) { address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId); return (_receiver, _creator, _tokenId); } return (_creator, _creator, _tokenId); } /// @notice If the token specified by token ID has been sold on the primary market function hadPrimarySaleOfToken(uint256 _tokenId) public override view returns (bool) { return owners[_tokenId] != address(0); } /// @notice If any token in the edition has been sold function hasMadePrimarySale(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] != address(0)) { return true; } } return false; } /// @notice If all tokens in the edition have been sold function isEditionSoldOut(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { return false; } } return true; } ////////////// // Defaults // ////////////// /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) override external { _safeTransferFrom(_from, _to, _tokenId, _data); // move the token emit Transfer(_from, _to, _tokenId); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) override external { _safeTransferFrom(_from, _to, _tokenId, bytes("")); // move the token emit Transfer(_from, _to, _tokenId); } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private { _transferFrom(_from, _to, _tokenId); uint256 receiverCodeSize; assembly { receiverCodeSize := extcodesize(_to) } if (receiverCodeSize > 0) { bytes4 selector = IERC721Receiver(_to).onERC721Received( _msgSender(), _from, _tokenId, _data ); require( selector == ERC721_RECEIVED, "Invalid selector" ); } } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `_msgSender()` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) override external { _transferFrom(_from, _to, _tokenId); // move the token emit Transfer(_from, _to, _tokenId); } function _transferFrom(address _from, address _to, uint256 _tokenId) private { // enforce not being able to send to zero as we have explicit rules what a minted but unbound owner is require(_to != address(0), "Invalid to address"); // Ensure the owner is the sender address owner = _ownerOf(_tokenId, _editionFromTokenId(_tokenId)); require(owner != address(0), "Invalid owner"); require(_from == owner, "Owner mismatch"); address spender = _msgSender(); address approvedAddress = getApproved(_tokenId); require( spender == owner // sending to myself || isApprovedForAll(owner, spender) // is approved to send any behalf of owner || approvedAddress == spender, // is approved to move this token ID "Invalid spender" ); // Ensure approval for token ID is cleared if (approvedAddress != address(0)) { approvals[_tokenId] = address(0); } // set new owner - this will now override any specific other mappings for the base edition config owners[_tokenId] = _to; // Modify balances balances[_from] = balances[_from] - 1; balances[_to] = balances[_to] + 1; } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) override public view returns (address) { uint256 editionId = _editionFromTokenId(_tokenId); address owner = _ownerOf(_tokenId, editionId); require(owner != address(0), "Invalid owner"); return owner; } /// @dev Newly created editions and its tokens minted to a creator don't have the owner set until the token is sold on the primary market /// @dev Therefore, if internally an edition exists and owner of token is zero address, then creator still owns the token /// @dev Otherwise, the token owner is returned or the zero address if the token does not exist function _ownerOf(uint256 _tokenId, uint256 _editionId) internal view returns (address) { // If an owner assigned address owner = owners[_tokenId]; if (owner != address(0)) { return owner; } // fall back to edition creator address possibleCreator = _getCreatorOfEdition(_editionId); if (possibleCreator != address(0) && (_maxTokenIdOfEdition(_editionId) - 1) >= _tokenId) { return possibleCreator; } return address(0); } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) override external { address owner = ownerOf(_tokenId); require(_approved != owner, "Approved is owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Invalid sender"); approvals[_tokenId] = _approved; emit Approval(owner, _approved, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`"s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) override external { operatorApprovals[_msgSender()][_operator] = _approved; emit ApprovalForAll( _msgSender(), _operator, _approved ); } /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) override external view returns (uint256) { require(_owner != address(0), "Invalid owner"); return balances[_owner]; } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) override public view returns (address){ return approvals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) override public view returns (bool){ return operatorApprovals[_owner][_operator]; } /// @notice An extension to the default ERC721 behaviour, derived from ERC-875. /// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens function batchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _safeTransferFrom(_from, _to, _tokenIds[i], bytes("")); emit Transfer(_from, _to, _tokenIds[i]); } } /// @notice An extension to the default ERC721 behaviour, derived from ERC-875 but using the ConsecutiveTransfer event /// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens function consecutiveBatchTransferFrom(address _from, address _to, uint256 _fromTokenId, uint256 _toTokenId) public { for (uint256 i = _fromTokenId; i <= _toTokenId; i++) { _safeTransferFrom(_from, _to, i, bytes("")); } emit ConsecutiveTransfer(_fromTokenId, _toTokenId, _from, _to); } ///////////////////// // Admin functions // ///////////////////// function setRoyaltiesRegistryProxy(IERC2981 _royaltiesRegistryProxy) onlyAdmin public { royaltiesRegistryProxy = _royaltiesRegistryProxy; emit AdminRoyaltiesRegistryProxySet(address(_royaltiesRegistryProxy)); } function setTokenUriResolver(ITokenUriResolver _tokenUriResolver) onlyAdmin public { tokenUriResolver = _tokenUriResolver; emit AdminTokenUriResolverSet(address(_tokenUriResolver)); } /////////////////////// // Creator functions // /////////////////////// function composeERC20sAsCreator(uint16 _editionId, address[] calldata _erc20s, uint256[] calldata _amounts) external validateCreator(_editionId) { require(!isEditionSoldOut(_editionId), "Edition soldout"); uint256 totalErc20s = _erc20s.length; require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid"); for (uint i = 0; i < totalErc20s; i++) { _composeERC20IntoEdition(_msgSender(), _editionId, _erc20s[i], _amounts[i]); } } /// @notice Optional metadata storage slot which allows the creator to set an additional metadata blob on the edition function lockInAdditionalMetaData(uint256 _editionId, string calldata _metadata) external validateCreator(_editionId) { require(bytes(sealedEditionMetaData[_editionId]).length == 0, "Already set"); sealedEditionMetaData[_editionId] = _metadata; emit SealedEditionMetaDataSet(_editionId); } /// @notice Optional metadata storage slot which allows a token owner to set an additional metadata blob on the token function lockInAdditionalTokenMetaData(uint256 _tokenId, string calldata _metadata) external { require( _msgSender() == ownerOf(_tokenId) || accessControls.hasContractRole(_msgSender()), "Invalid caller" ); require(bytes(sealedTokenMetaData[_tokenId]).length == 0, "Already set"); sealedTokenMetaData[_tokenId] = _metadata; emit SealedTokenMetaDataSet(_tokenId); } }
@notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE THEY MAY BE PERMANENTLY LOST @dev Throws unless `_msgSender()` is the current owner, an authorized operator, or the approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero address. Throws if `_tokenId` is not a valid NFT. @param _from The current owner of the NFT @param _to The new owner @param _tokenId The NFT to transfer move the token
function transferFrom(address _from, address _to, uint256 _tokenId) override external { _transferFrom(_from, _to, _tokenId); emit Transfer(_from, _to, _tokenId); }
105,842
[ 1, 5912, 23178, 434, 392, 423, 4464, 1493, 12786, 22753, 654, 4437, 2438, 10789, 16645, 540, 8493, 3492, 31324, 7662, 789, 1375, 67, 869, 68, 4437, 29720, 2782, 15932, 2438, 1441, 8188, 1360, 423, 4464, 55, 4869, 14801, 1090, 540, 7662, 2602, 490, 5255, 9722, 10950, 9560, 2222, 7076, 1806, 882, 225, 22435, 3308, 1375, 67, 3576, 12021, 20338, 353, 326, 783, 3410, 16, 392, 10799, 1377, 3726, 16, 578, 326, 20412, 1758, 364, 333, 423, 4464, 18, 22435, 309, 1375, 67, 2080, 68, 353, 1377, 486, 326, 783, 3410, 18, 22435, 309, 1375, 67, 869, 68, 353, 326, 3634, 1758, 18, 22435, 309, 1377, 1375, 67, 2316, 548, 68, 353, 486, 279, 923, 423, 4464, 18, 225, 389, 2080, 1021, 783, 3410, 434, 326, 423, 4464, 225, 389, 869, 1021, 394, 3410, 225, 389, 2316, 548, 1021, 423, 4464, 358, 7412, 3635, 326, 1147, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 3849, 3903, 288, 203, 3639, 389, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 2316, 548, 1769, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8C2f976b1f6F5f2867a8B560BdbF244C5e263Ca6/sources/src/interfaces/seaport/ISeaport.sol
* @notice Retrieve the current counter for a given offerer. @param offerer The offerer in question. @return counter The current counter./* @notice Retrieve the status of a given order by hash, including whether the order has been cancelled or validated and the fraction of the order that has been filled. @param orderHash The order hash in question. @return isValidated A boolean indicating whether the order in question has been validated (i.e. previously approved or partially filled). @return isCancelled A boolean indicating whether the order in question has been cancelled. @return totalFilled The total portion of the order that has been filled (i.e. the "numerator"). @return totalSize The total size of the order that is either filled or unfilled (i.e. the "denominator")./* @notice Retrieve the order hash for a given order. @param order The components of the order. @return orderHash The order hash./* @dev An order contains eleven components: an offerer, a zone (or account that can cancel the order or restrict who can fulfill the order depending on the type), the order type (specifying partial fill support as well as restricted order status), the start and end time, a hash that will be provided to the zone when validating restricted orders, a salt, a key corresponding to a given conduit, a counter, and an arbitrary number of offer items that can be spent along with consideration items that must be received by their respective recipient./
function getCounter(address offerer) external view returns (uint256 counter); function getOrderStatus( bytes32 orderHash ) external view returns (bool isValidated, bool isCancelled, uint256 totalFilled, uint256 totalSize); function getOrderHash(OrderComponents calldata order) external view returns (bytes32 orderHash); struct OrderComponents { address offerer; address zone; OfferItem[] offer; ConsiderationItem[] consideration; OrderType orderType; uint256 startTime; uint256 endTime; bytes32 zoneHash; uint256 salt; bytes32 conduitKey; uint256 counter; }
16,025,995
[ 1, 5767, 326, 783, 3895, 364, 279, 864, 10067, 264, 18, 225, 10067, 264, 1021, 10067, 264, 316, 5073, 18, 327, 3895, 1021, 783, 3895, 18, 19, 225, 10708, 326, 1267, 434, 279, 864, 1353, 635, 1651, 16, 6508, 2856, 540, 326, 1353, 711, 2118, 13927, 578, 10266, 471, 326, 8330, 434, 326, 540, 1353, 716, 711, 2118, 6300, 18, 225, 1353, 2310, 1021, 1353, 1651, 316, 5073, 18, 327, 4908, 690, 432, 1250, 11193, 2856, 326, 1353, 316, 5073, 5397, 711, 2118, 10266, 261, 77, 18, 73, 18, 7243, 20412, 578, 5397, 19976, 6300, 2934, 327, 353, 21890, 432, 1250, 11193, 2856, 326, 1353, 316, 5073, 5397, 711, 2118, 13927, 18, 327, 2078, 29754, 1021, 2078, 14769, 434, 326, 1353, 716, 711, 2118, 6300, 5397, 261, 77, 18, 73, 18, 326, 315, 2107, 7385, 20387, 327, 24611, 282, 1021, 2078, 963, 434, 326, 1353, 716, 353, 3344, 6300, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 31107, 12, 2867, 10067, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 3895, 1769, 203, 203, 565, 445, 11973, 1482, 12, 203, 3639, 1731, 1578, 1353, 2310, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 4908, 690, 16, 1426, 353, 21890, 16, 2254, 5034, 2078, 29754, 16, 2254, 5034, 24611, 1769, 203, 203, 565, 445, 11973, 2310, 12, 2448, 7171, 745, 892, 1353, 13, 3903, 1476, 1135, 261, 3890, 1578, 1353, 2310, 1769, 203, 203, 565, 1958, 4347, 7171, 288, 203, 3639, 1758, 10067, 264, 31, 203, 3639, 1758, 4157, 31, 203, 3639, 25753, 1180, 8526, 10067, 31, 203, 3639, 23047, 367, 1180, 8526, 5260, 367, 31, 203, 3639, 4347, 559, 1353, 559, 31, 203, 3639, 2254, 5034, 8657, 31, 203, 3639, 2254, 5034, 13859, 31, 203, 3639, 1731, 1578, 4157, 2310, 31, 203, 3639, 2254, 5034, 4286, 31, 203, 3639, 1731, 1578, 356, 2544, 305, 653, 31, 203, 3639, 2254, 5034, 3895, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD62A80368AdF5919f70193D15dCbD5C77EAf55ac/sources/src/Vault.sol
@notice Set the issuance module for the vault @param _issuance The issuance module address @dev only owner
function setIssuance(address _issuance) external only(owner()) { issuance = _issuance; emit VaultIssuanceSet(_issuance); }
3,028,562
[ 1, 694, 326, 3385, 89, 1359, 1605, 364, 326, 9229, 225, 389, 1054, 89, 1359, 1021, 3385, 89, 1359, 1605, 1758, 225, 1338, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 7568, 89, 1359, 12, 2867, 389, 1054, 89, 1359, 13, 3903, 1338, 12, 8443, 10756, 288, 203, 3639, 3385, 89, 1359, 273, 389, 1054, 89, 1359, 31, 203, 3639, 3626, 17329, 7568, 89, 1359, 694, 24899, 1054, 89, 1359, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2aaC69aCac4b14df223871b4707baaF71613a799/sources/project_/contracts/util/Util.sol
* Converts the given USD amount to MATIC using the current price from Chainlink @param usdAmount amount of USD to convert @param usdDecimals decimals of USD amount @param priceFeed Feed of price convert/ Round up the last two decimals
function convertUSDtoMATIC(uint256 usdAmount, uint8 usdDecimals, AggregatorV3Interface priceFeed) public view returns (uint256) { (, int rate, , ,) = priceFeed.latestRoundData(); uint8 rateDecimals = priceFeed.decimals(); require(rate > 0, "Price feed error"); uint256 scaleFactor = 10 ** (rateDecimals + usdDecimals - 8); uint256 maticAmount = usdAmount * scaleFactor / uint256(rate); uint256 roundedMaticAmount = maticAmount + 99; roundedMaticAmount = roundedMaticAmount / 100 * 100; return roundedMaticAmount; }
9,471,300
[ 1, 5692, 326, 864, 587, 9903, 3844, 358, 490, 11781, 1450, 326, 783, 6205, 628, 7824, 1232, 225, 584, 72, 6275, 3844, 434, 587, 9903, 358, 1765, 225, 584, 72, 31809, 15105, 434, 587, 9903, 3844, 225, 6205, 8141, 14013, 434, 6205, 1765, 19, 11370, 731, 326, 1142, 2795, 15105, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1765, 3378, 15389, 49, 11781, 12, 11890, 5034, 584, 72, 6275, 16, 2254, 28, 584, 72, 31809, 16, 10594, 639, 58, 23, 1358, 6205, 8141, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 16, 509, 4993, 16, 269, 269, 13, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 2254, 28, 4993, 31809, 273, 6205, 8141, 18, 31734, 5621, 203, 203, 3639, 2583, 12, 5141, 405, 374, 16, 315, 5147, 4746, 555, 8863, 203, 203, 3639, 2254, 5034, 3159, 6837, 273, 1728, 2826, 261, 5141, 31809, 397, 584, 72, 31809, 300, 1725, 1769, 203, 3639, 2254, 5034, 312, 2126, 6275, 273, 584, 72, 6275, 380, 3159, 6837, 342, 2254, 5034, 12, 5141, 1769, 203, 203, 3639, 2254, 5034, 16729, 49, 2126, 6275, 273, 312, 2126, 6275, 397, 14605, 31, 203, 3639, 16729, 49, 2126, 6275, 273, 16729, 49, 2126, 6275, 342, 2130, 380, 2130, 31, 203, 203, 3639, 327, 16729, 49, 2126, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]