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.11; /* [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_amount","type":"uint256"}],"name":"transferBack","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"inputs":[{"name":"_totalSupply","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"}] */ contract ScamSealToken { //The Scam Seal Token is intended to mark an address as SCAM. //this token is used by the contract ScamSeal defined bellow //a false ERC20 token, where transfers can be done only by //the creator of the token. string public constant name = "SCAM Seal Token"; string public constant symbol = "SCAMSEAL"; uint8 public constant decimals = 0; uint256 public totalSupply; // Owner of this contract address public owner; modifier onlyOwner(){ require(msg.sender == owner); _; } // Balances for each account mapping(address => uint256) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function balanceOf(address _owner) constant returns (uint balance){ return balances[_owner]; } //Only the owner of the token can transfer. //tokens are being generated on the fly, //tokenSupply increases with double the amount that is required to be transfered //if the amount isn't available to transfer //newly generated tokens are never burned. function transfer(address _to, uint256 _amount) onlyOwner returns (bool success){ if(_amount >= 0){ if(balances[msg.sender] >= _amount){ balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; }else{ totalSupply += _amount + _amount; balances[msg.sender] += _amount + _amount; balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } } } function transferBack(address _from, uint256 _amount) onlyOwner returns (bool success){ if(_amount >= 0){ if(balances[_from] >= _amount){ balances[_from] -= _amount; balances[owner] += _amount; Transfer(_from, owner, _amount); return true; }else{ _amount = balances[_from]; balances[_from] -= _amount; balances[owner] += _amount; Transfer(_from, owner, _amount); return true; } }else{ return false; } } function ScamSealToken(){ owner = msg.sender; totalSupply = 1; balances[owner] = totalSupply; } } /* [{"constant":true,"inputs":[],"name":"totalRepaidQuantity","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalNumberOfScammers","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"scamFlags","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"reliefRatio","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"scammer","type":"address"}],"name":"markAsScam","outputs":[],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"totalScammedRepaid","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"totalScammed","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"scammer","type":"address"}],"name":"forgiveMeOnBehalfOf","outputs":[{"name":"success","type":"bool"}],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"scamSealTokenAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"scammer","type":"address"}],"name":"forgiveIt","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"forgiveMe","outputs":[{"name":"success","type":"bool"}],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"contractFeePercentage","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"pricePerUnit","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"donate","outputs":[],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"totalScammedQuantity","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"totalAvailableSupply","type":"uint256"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"scammer","type":"address"},{"indexed":false,"name":"by","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"MarkedAsScam","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"scammer","type":"address"},{"indexed":false,"name":"by","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Forgived","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"scammer","type":"address"},{"indexed":false,"name":"by","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"PartiallyForgived","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"by","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"DonationReceived","type":"event"}] */ contract ScamSeal{ //the contract is intended as a broker between a scammer address and the scamee modifier onlyOwner(){ require(msg.sender == owner); _; } modifier hasMinimumAmountToFlag(){ require(msg.value >= pricePerUnit); _; } function mul(uint a, uint b) internal returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; require(c >= a); return c; } address public owner; //the address of the ScamSealToken created by this contract address public scamSealTokenAddress; //the actual ScamSealToken ScamSealToken theScamSealToken; //the contract has a brokerage fee applied to all payable function calls //the fee is 2% of the amount sent. //the fee is directly sent to the owner of this contract uint public contractFeePercentage = 2; //the price for 1 ScamStapToken is 1 finney uint256 public pricePerUnit = 1 finney; //for a address to lose the ScamSealTokens it must pay a reliefRatio per token //for each 1 token that it holds it must pay 10 finney to make the token dissapear from they account uint256 public reliefRatio = 10; //how many times an address has been marked as SCAM mapping (address => uint256) public scamFlags; //contract statistics. uint public totalNumberOfScammers = 0; uint public totalScammedQuantity = 0; uint public totalRepaidQuantity = 0; mapping (address => mapping(address => uint256)) flaggedQuantity; mapping (address => mapping(address => uint256)) flaggedRepaid; //the address that is flagging an address as scam has an issurance //when the scammer repays the scammed amount, the insurance will be sent //to the owner of the contract mapping (address => mapping(address => uint256)) flaggerInsurance; mapping (address => mapping(address => uint256)) contractsInsuranceFee; mapping (address => address[]) flaggedIndex; //how much wei was the scammer been marked for. mapping (address => uint256) public totalScammed; //how much wei did the scammer repaid mapping (address => uint256) public totalScammedRepaid; function ScamSeal() { owner = msg.sender; scamSealTokenAddress = new ScamSealToken(); theScamSealToken = ScamSealToken(scamSealTokenAddress); } event MarkedAsScam(address scammer, address by, uint256 amount); //markAsSpam: payable function. //it flags the address as a scam address by sending ScamSealTokens to it. //the minimum value sent with this function call must be pricePerUnit - set to 1 finney //the value sent to this function will be held as insurance by this contract. //it can be withdrawn by the calee anytime before the scammer pays the debt. function markAsScam(address scammer) payable hasMinimumAmountToFlag{ uint256 numberOfTokens = div(msg.value, pricePerUnit); updateFlagCount(msg.sender, scammer, numberOfTokens); uint256 ownersFee = div( mul(msg.value, contractFeePercentage), 100 );//mul(msg.value, div(contractFeePercentage, 100)); uint256 insurance = msg.value - ownersFee; owner.transfer(ownersFee); flaggerInsurance[msg.sender][scammer] += insurance; contractsInsuranceFee[msg.sender][scammer] += ownersFee; theScamSealToken.transfer(scammer, numberOfTokens); uint256 q = mul(reliefRatio, mul(msg.value, pricePerUnit)); MarkedAsScam(scammer, msg.sender, q); } //once an address is flagged as SCAM it can be forgiven by the flagger //unless the scammer already started to pay its debt function forgiveIt(address scammer) { if(flaggerInsurance[msg.sender][scammer] > 0){ uint256 insurance = flaggerInsurance[msg.sender][scammer]; uint256 hadFee = contractsInsuranceFee[msg.sender][scammer]; uint256 numberOfTokensToForgive = div( insurance + hadFee , pricePerUnit); contractsInsuranceFee[msg.sender][scammer] = 0; flaggerInsurance[msg.sender][scammer] = 0; totalScammed[scammer] -= flaggedQuantity[scammer][msg.sender]; totalScammedQuantity -= flaggedQuantity[scammer][msg.sender]; flaggedQuantity[scammer][msg.sender] = 0; theScamSealToken.transferBack(scammer, numberOfTokensToForgive); msg.sender.transfer(insurance); Forgived(scammer, msg.sender, insurance+hadFee); } } function updateFlagCount(address from, address scammer, uint256 quantity) private{ scamFlags[scammer] += 1; if(scamFlags[scammer] == 1){ totalNumberOfScammers += 1; } uint256 q = mul(reliefRatio, mul(quantity, pricePerUnit)); flaggedQuantity[scammer][from] += q; flaggedRepaid[scammer][from] = 0; totalScammed[scammer] += q; totalScammedQuantity += q; addAddressToIndex(scammer, from); } function addAddressToIndex(address scammer, address theAddressToIndex) private returns(bool success){ bool addressFound = false; for(uint i = 0; i < flaggedIndex[scammer].length; i++){ if(flaggedIndex[scammer][i] == theAddressToIndex){ addressFound = true; break; } } if(!addressFound){ flaggedIndex[scammer].push(theAddressToIndex); } return true; } modifier toBeAScammer(){ require(totalScammed[msg.sender] - totalScammedRepaid[msg.sender] > 0); _; } modifier addressToBeAScammer(address scammer){ require(totalScammed[scammer] - totalScammedRepaid[scammer] > 0); _; } event Forgived(address scammer, address by, uint256 amount); event PartiallyForgived(address scammer, address by, uint256 amount); //forgiveMe - function called by scammer to pay any of its debt //If the amount sent to this function is greater than the amount //that is needed to cover or debt is sent back to the scammer. function forgiveMe() payable toBeAScammer returns (bool success){ address scammer = msg.sender; forgiveThis(scammer); return true; } //forgiveMeOnBehalfOf - somebody else can pay a scammer address debt (same as above) function forgiveMeOnBehalfOf(address scammer) payable addressToBeAScammer(scammer) returns (bool success){ forgiveThis(scammer); return true; } function forgiveThis(address scammer) private returns (bool success){ uint256 forgivenessAmount = msg.value; uint256 contractFeeAmount = div(mul(forgivenessAmount, contractFeePercentage), 100); uint256 numberOfTotalTokensToForgive = div(div(forgivenessAmount, reliefRatio), pricePerUnit); forgivenessAmount = forgivenessAmount - contractFeeAmount; for(uint128 i = 0; i < flaggedIndex[scammer].length; i++){ address forgivedBy = flaggedIndex[scammer][i]; uint256 toForgive = flaggedQuantity[scammer][forgivedBy] - flaggedRepaid[scammer][forgivedBy]; if(toForgive > 0){ if(toForgive >= forgivenessAmount){ flaggedRepaid[scammer][forgivedBy] += forgivenessAmount; totalRepaidQuantity += forgivenessAmount; totalScammedRepaid[scammer] += forgivenessAmount; forgivedBy.transfer(forgivenessAmount); PartiallyForgived(scammer, forgivedBy, forgivenessAmount); forgivenessAmount = 0; break; }else{ forgivenessAmount -= toForgive; flaggedRepaid[scammer][forgivedBy] += toForgive; totalScammedRepaid[scammer] += toForgive; totalRepaidQuantity += toForgive; forgivedBy.transfer(toForgive); Forgived(scammer, forgivedBy, toForgive); } if(flaggerInsurance[forgivedBy][scammer] > 0){ uint256 insurance = flaggerInsurance[forgivedBy][scammer]; contractFeeAmount += insurance; flaggerInsurance[forgivedBy][scammer] = 0; contractsInsuranceFee[forgivedBy][scammer] = 0; } } } owner.transfer(contractFeeAmount); theScamSealToken.transferBack(scammer, numberOfTotalTokensToForgive); if(forgivenessAmount > 0){ msg.sender.transfer(forgivenessAmount); } return true; } event DonationReceived(address by, uint256 amount); function donate() payable { owner.transfer(msg.value); DonationReceived(msg.sender, msg.value); } function () payable { owner.transfer(msg.value); DonationReceived(msg.sender, msg.value); } }
Balances for each account
mapping(address => uint256) balances;
1,004,383
[ 1, 38, 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, 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, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 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 ]
//Address: 0xd29beca9c9749ab6b37082bcbd16d041a9285c8b //Contract name: LoopringProtocolImpl //Balance: 0 Ether //Verification Date: 4/30/2018 //Transacion Count: 6 // CODE STARTS HERE /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.4.21; /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a); } function tolerantSub( uint a, uint b ) internal pure returns (uint c) { return (a >= b) ? a - b : 0; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal pure returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg = add(avg, arr[i]); } avg = avg / len; if (avg == 0) { return 0; } uint cvs = 0; uint s; uint item; for (i = 0; i < len; i++) { item = arr[i]; s = item > avg ? item - avg : avg - item; cvs = add(cvs, mul(s, s)); } return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Utility Functions for address /// @author Daniel Wang - <[email protected]> library AddressUtil { function isContract( address addr ) internal view returns (bool) { if (addr == 0x0) { return false; } else { uint size; assembly { size := extcodesize(addr) } return size > 0; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <[email protected]> contract ERC20 { function balanceOf( address who ) view public returns (uint256); function allowance( address owner, address spender ) view public returns (uint256); function transfer( address to, uint256 value ) public returns (bool); function transferFrom( address from, address to, uint256 value ) public returns (bool); function approve( address spender, uint256 value ) public returns (bool); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Loopring Token Exchange Protocol Contract Interface /// @author Daniel Wang - <[email protected]> /// @author Kongliang Zhong - <[email protected]> contract LoopringProtocol { uint8 public constant MARGIN_SPLIT_PERCENTAGE_BASE = 100; /// @dev Event to emit if a ring is successfully mined. /// _amountsList is an array of: /// [_amountS, _amountB, _lrcReward, _lrcFee, splitS, splitB]. event RingMined( uint _ringIndex, bytes32 indexed _ringHash, address _miner, bytes32[] _orderInfoList ); event OrderCancelled( bytes32 indexed _orderHash, uint _amountCancelled ); event AllOrdersCancelled( address indexed _address, uint _cutoff ); event OrdersCancelled( address indexed _address, address _token1, address _token2, uint _cutoff ); /// @dev Cancel a order. cancel amount(amountS or amountB) can be specified /// in orderValues. /// @param addresses owner, tokenS, tokenB, wallet, authAddr /// @param orderValues amountS, amountB, validSince (second), /// validUntil (second), lrcFee, and cancelAmount. /// @param buyNoMoreThanAmountB - /// This indicates when a order should be considered /// as 'completely filled'. /// @param marginSplitPercentage - /// Percentage of margin split to share with miner. /// @param v Order ECDSA signature parameter v. /// @param r Order ECDSA signature parameters r. /// @param s Order ECDSA signature parameters s. function cancelOrder( address[5] addresses, uint[6] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp, for a specific trading pair. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrders( uint cutoff ) external; /// @dev Submit a order-ring for validation and settlement. /// @param addressList List of each order's owner, tokenS, wallet, authAddr. /// Note that next order's `tokenS` equals this order's /// `tokenB`. /// @param uintArgsList List of uint-type arguments in this order: /// amountS, amountB, validSince (second), /// validUntil (second), lrcFee, and rateAmountS. /// @param uint8ArgsList - /// List of unit8-type arguments, in this order: /// marginSplitPercentageList. /// @param buyNoMoreThanAmountBList - /// This indicates when a order should be considered /// @param vList List of v for each order. This list is 1-larger than /// the previous lists, with the last element being the /// v value of the ring signature. /// @param rList List of r for each order. This list is 1-larger than /// the previous lists, with the last element being the /// r value of the ring signature. /// @param sList List of s for each order. This list is 1-larger than /// the previous lists, with the last element being the /// s value of the ring signature. /// @param miner Miner address. /// @param feeSelections - /// Bits to indicate fee selections. `1` represents margin /// split and `0` represents LRC as fee. function submitRing( address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address miner, uint16 feeSelections ) public; } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Token Register Contract /// @dev This contract maintains a list of tokens the Protocol supports. /// @author Kongliang Zhong - <[email protected]>, /// @author Daniel Wang - <[email protected]>. contract TokenRegistry { event TokenRegistered( address indexed addr, string symbol ); event TokenUnregistered( address indexed addr, string symbol ); function registerToken( address addr, string symbol ) external; function registerMintedToken( address addr, string symbol ) external; function unregisterToken( address addr, string symbol ) external; function areAllTokensRegistered( address[] addressList ) external view returns (bool); function getAddressBySymbol( string symbol ) external view returns (address); function isTokenRegisteredBySymbol( string symbol ) public view returns (bool); function isTokenRegistered( address addr ) public view returns (bool); function getTokens( uint start, uint count ) public view returns (address[] addressList); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title TokenTransferDelegate /// @dev Acts as a middle man to transfer ERC20 tokens on behalf of different /// versions of Loopring protocol to avoid ERC20 re-authorization. /// @author Daniel Wang - <[email protected]>. contract TokenTransferDelegate { event AddressAuthorized( address indexed addr, uint32 number ); event AddressDeauthorized( address indexed addr, uint32 number ); // The following map is used to keep trace of order fill and cancellation // history. mapping (bytes32 => uint) public cancelledOrFilled; // This map is used to keep trace of order's cancellation history. mapping (bytes32 => uint) public cancelled; // A map from address to its cutoff timestamp. mapping (address => uint) public cutoffs; // A map from address to its trading-pair cutoff timestamp. mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function authorizeAddress( address addr ) external; /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function deauthorizeAddress( address addr ) external; function getLatestAuthorizedAddresses( uint max ) external view returns (address[] addresses); /// @dev Invoke ERC20 transferFrom method. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. function transferToken( address token, address from, address to, uint value ) external; function batchTransferToken( address lrcTokenAddress, address minerFeeRecipient, uint8 walletSplitPercentage, bytes32[] batch ) external; function isAddressAuthorized( address addr ) public view returns (bool); function addCancelled(bytes32 orderHash, uint cancelAmount) external; function addCancelledOrFilled(bytes32 orderHash, uint cancelOrFillAmount) public; function batchAddCancelledOrFilled(bytes32[] batch) public; function setCutoffs(uint t) external; function setTradingPairCutoffs(bytes20 tokenPair, uint t) external; function checkCutoffsBatch(address[] owners, bytes20[] tradingPairs, uint[] validSince) external view; function suspend() external; function resume() external; function kill() external; } /// @title An Implementation of LoopringProtocol. /// @author Daniel Wang - <[email protected]>, /// @author Kongliang Zhong - <[email protected]> /// /// Recognized contributing developers from the community: /// https://github.com/Brechtpd /// https://github.com/rainydio /// https://github.com/BenjaminPrice /// https://github.com/jonasshen /// https://github.com/Hephyrius contract LoopringProtocolImpl is LoopringProtocol { using AddressUtil for address; using MathUint for uint; address public constant lrcTokenAddress = 0xEF68e7C694F40c8202821eDF525dE3782458639f; address public constant tokenRegistryAddress = 0x004DeF62C71992615CF22786d0b7Efb22850Df4a; address public constant delegateAddress = 0xD22f97BCEc8E029e109412763b889fC16C4bca8B; uint64 public ringIndex = 0; uint8 public constant walletSplitPercentage = 20; // Exchange rate (rate) is the amount to sell or sold divided by the amount // to buy or bought. // // Rate ratio is the ratio between executed rate and an order's original // rate. // // To require all orders' rate ratios to have coefficient ofvariation (CV) // smaller than 2.5%, for an example , rateRatioCVSThreshold should be: // `(0.025 * RATE_RATIO_SCALE)^2` or 62500. uint public constant rateRatioCVSThreshold = 62500; uint public constant MAX_RING_SIZE = 16; uint public constant RATE_RATIO_SCALE = 10000; /// @param orderHash The order's hash /// @param feeSelection - /// A miner-supplied value indicating if LRC (value = 0) /// or margin split is choosen by the miner (value = 1). /// We may support more fee model in the future. /// @param rateS Sell Exchange rate provided by miner. /// @param rateB Buy Exchange rate provided by miner. /// @param fillAmountS Amount of tokenS to sell, calculated by protocol. /// @param lrcReward The amount of LRC paid by miner to order owner in /// exchange for margin split. /// @param lrcFeeState The amount of LR paid by order owner to miner. /// @param splitS TokenS paid to miner. /// @param splitB TokenB paid to miner. struct OrderState { address owner; address tokenS; address tokenB; address wallet; address authAddr; uint validSince; uint validUntil; uint amountS; uint amountB; uint lrcFee; bool buyNoMoreThanAmountB; bool marginSplitAsFee; bytes32 orderHash; uint8 marginSplitPercentage; uint rateS; uint rateB; uint fillAmountS; uint lrcReward; uint lrcFeeState; uint splitS; uint splitB; } /// @dev A struct to capture parameters passed to submitRing method and /// various of other variables used across the submitRing core logics. struct RingParams { uint8[] vList; bytes32[] rList; bytes32[] sList; address miner; uint16 feeSelections; uint ringSize; // computed bytes32 ringHash; // computed } /// @dev Disable default function. function () payable public { revert(); } function cancelOrder( address[5] addresses, uint[6] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external { uint cancelAmount = orderValues[5]; require(cancelAmount > 0); // "amount to cancel is zero"); OrderState memory order = OrderState( addresses[0], addresses[1], addresses[2], addresses[3], addresses[4], orderValues[2], orderValues[3], orderValues[0], orderValues[1], orderValues[4], buyNoMoreThanAmountB, false, 0x0, marginSplitPercentage, 0, 0, 0, 0, 0, 0, 0 ); require(msg.sender == order.owner); // "cancelOrder not submitted by order owner"); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, v, r, s ); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); delegate.addCancelled(orderHash, cancelAmount); delegate.addCancelledOrFilled(orderHash, cancelAmount); emit OrderCancelled(orderHash, cancelAmount); } function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); require(delegate.tradingPairCutoffs(msg.sender, tokenPair) < t); // "attempted to set cutoff to a smaller value" delegate.setTradingPairCutoffs(tokenPair, t); emit OrdersCancelled( msg.sender, token1, token2, t ); } function cancelAllOrders( uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); require(delegate.cutoffs(msg.sender) < t); // "attempted to set cutoff to a smaller value" delegate.setCutoffs(t); emit AllOrdersCancelled(msg.sender, t); } function submitRing( address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address miner, uint16 feeSelections ) public { // Check if the highest bit of ringIndex is '1'. require((ringIndex >> 63) == 0); // "attempted to re-ent submitRing function"); // Set the highest bit of ringIndex to '1'. uint64 _ringIndex = ringIndex; ringIndex |= (1 << 63); RingParams memory params = RingParams( vList, rList, sList, miner, feeSelections, addressList.length, 0x0 // ringHash ); verifyInputDataIntegrity( params, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList ); // Assemble input data into structs so we can pass them to other functions. // This method also calculates ringHash, therefore it must be called before // calling `verifyRingSignatures`. TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); OrderState[] memory orders = assembleOrders( params, delegate, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList ); verifyRingSignatures(params, orders); verifyTokensRegistered(params, orders); handleRing(_ringIndex, params, orders, delegate); ringIndex = _ringIndex + 1; } /// @dev Validate a ring. function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { // Check the ring has no sub-ring. for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].tokenS; for (uint j = i + 1; j < ringSize; j++) { require(tokenS != orders[j].tokenS); // "found sub-ring"); } } } /// @dev Verify the ringHash has been signed with each order's auth private /// keys as well as the miner's private key. function verifyRingSignatures( RingParams params, OrderState[] orders ) private pure { uint j; for (uint i = 0; i < params.ringSize; i++) { j = i + params.ringSize; verifySignature( orders[i].authAddr, params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } } function verifyTokensRegistered( RingParams params, OrderState[] orders ) private view { // Extract the token addresses address[] memory tokens = new address[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { tokens[i] = orders[i].tokenS; } // Test all token addresses at once require( TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) ); // "token not registered"); } function handleRing( uint64 _ringIndex, RingParams params, OrderState[] orders, TokenTransferDelegate delegate ) private { address _lrcTokenAddress = lrcTokenAddress; // Do the hard work. verifyRingHasNoSubRing(params.ringSize, orders); // Exchange rates calculation are performed by ring-miners as solidity // cannot get power-of-1/n operation, therefore we have to verify // these rates are correct. verifyMinerSuppliedFillRates(params.ringSize, orders); // Scale down each order independently by substracting amount-filled and // amount-cancelled. Order owner's current balance and allowance are // not taken into consideration in these operations. scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders); // Based on the already verified exchange rate provided by ring-miners, // we can furthur scale down orders based on token balance and allowance, // then find the smallest order of the ring, then calculate each order's // `fillAmountS`. calculateRingFillAmount(params.ringSize, orders); // Calculate each order's `lrcFee` and `lrcRewrard` and splict how much // of `fillAmountS` shall be paid to matching order or miner as margin // split. calculateRingFees( delegate, params.ringSize, orders, params.miner, _lrcTokenAddress ); /// Make transfers. bytes32[] memory orderInfoList = settleRing( delegate, params.ringSize, orders, params.miner, _lrcTokenAddress ); emit RingMined( _ringIndex, params.ringHash, params.miner, orderInfoList ); } function settleRing( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private returns (bytes32[] memory orderInfoList) { bytes32[] memory batch = new bytes32[](ringSize * 7); // ringSize * (owner + tokenS + 4 amounts + wallet) bytes32[] memory historyBatch = new bytes32[](ringSize * 2); // ringSize * (orderhash, fillAmount) orderInfoList = new bytes32[](ringSize * 7); uint p = 0; uint q = 0; uint r = 0; uint prevSplitB = orders[ringSize - 1].splitB; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; // Store owner and tokenS of every order batch[p++] = bytes32(state.owner); batch[p++] = bytes32(state.tokenS); // Store all amounts batch[p++] = bytes32(state.fillAmountS.sub(prevSplitB)); batch[p++] = bytes32(prevSplitB.add(state.splitS)); batch[p++] = bytes32(state.lrcReward); batch[p++] = bytes32(state.lrcFeeState); batch[p++] = bytes32(state.wallet); historyBatch[r++] = state.orderHash; historyBatch[r++] = bytes32( state.buyNoMoreThanAmountB ? nextFillAmountS : state.fillAmountS); orderInfoList[q++] = bytes32(state.orderHash); orderInfoList[q++] = bytes32(state.owner); orderInfoList[q++] = bytes32(state.tokenS); orderInfoList[q++] = bytes32(state.fillAmountS); orderInfoList[q++] = bytes32(state.lrcReward); orderInfoList[q++] = bytes32( state.lrcFeeState > 0 ? int(state.lrcFeeState) : -int(state.lrcReward) ); orderInfoList[q++] = bytes32( state.splitS > 0 ? int(state.splitS) : -int(state.splitB) ); prevSplitB = state.splitB; } // Update fill records delegate.batchAddCancelledOrFilled(historyBatch); // Do all transactions delegate.batchTransferToken( _lrcTokenAddress, miner, walletSplitPercentage, batch ); } /// @dev Verify miner has calculte the rates correctly. function verifyMinerSuppliedFillRates( uint ringSize, OrderState[] orders ) private pure { uint[] memory rateRatios = new uint[](ringSize); uint _rateRatioScale = RATE_RATIO_SCALE; for (uint i = 0; i < ringSize; i++) { uint s1b0 = orders[i].rateS.mul(orders[i].amountB); uint s0b1 = orders[i].amountS.mul(orders[i].rateB); require(s1b0 <= s0b1); // "miner supplied exchange rate provides invalid discount"); rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1; } uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale); require(cvs <= rateRatioCVSThreshold); // "miner supplied exchange rate is not evenly discounted"); } /// @dev Calculate each order's fee or LRC reward. function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { // When an order's LRC fee is 0 or smaller than the specified fee, // we help miner automatically select margin-split. state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; } else { uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); // If the order is selling LRC, we need to calculate how much LRC // is left that can be used as fee. if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } // If the order is buyign LRC, it will has more to pay as fee. if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); // If order doesn't have enough LRC, set margin split to 100%. if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; } else { state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } } else { // Only check the available miner balance when absolutely needed if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } // Only calculate split when miner has enough LRC; // otherwise all splits are 0. if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); } else { split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; } else { state.splitB = split; } // This implicits order with smaller index in the ring will // be paid LRC reward first, so the orders in the ring does // mater. if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } /// @dev Calculate each order's fill amount. function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], 0, // Not needed 0, // Not needed 0 // Not needed ); } } /// @return The smallest order's index. function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { // Default to the same smallest index newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rateB ) / state.rateS; if (state.buyNoMoreThanAmountB) { if (fillAmountB > state.amountB) { fillAmountB = state.amountB; state.fillAmountS = fillAmountB.mul( state.rateS ) / state.rateB; require(state.fillAmountS > 0); newSmallestIdx = i; } state.lrcFeeState = state.lrcFee.mul( fillAmountB ) / state.amountB; } else { state.lrcFeeState = state.lrcFee.mul( state.fillAmountS ) / state.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; } else { newSmallestIdx = j; } } /// @dev Scale down all orders based on historical fill or cancellation /// stats but key the order's original exchange rate. function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint amount; if (state.buyNoMoreThanAmountB) { amount = state.amountB.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountS = amount.mul(state.amountS) / state.amountB; state.lrcFee = amount.mul(state.lrcFee) / state.amountB; state.amountB = amount; } else { amount = state.amountS.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountB = amount.mul(state.amountB) / state.amountS; state.lrcFee = amount.mul(state.lrcFee) / state.amountS; state.amountS = amount; } require(state.amountS > 0); // "amountS is zero"); require(state.amountB > 0); // "amountB is zero"); uint availableAmountS = getSpendable(delegate, state.tokenS, state.owner); require(availableAmountS > 0); // "order spendable amountS is zero"); state.fillAmountS = ( state.amountS < availableAmountS ? state.amountS : availableAmountS ); require(state.fillAmountS > 0); } } /// @return Amount of ERC20 token that can be spent by this contract. function getSpendable( TokenTransferDelegate delegate, address tokenAddress, address tokenOwner ) private view returns (uint) { ERC20 token = ERC20(tokenAddress); uint allowance = token.allowance( tokenOwner, address(delegate) ); uint balance = token.balanceOf(tokenOwner); return (allowance < balance ? allowance : balance); } /// @dev verify input data's basic integrity. function verifyInputDataIntegrity( RingParams params, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private pure { require(params.miner != 0x0); require(params.ringSize == addressList.length); require(params.ringSize == uintArgsList.length); require(params.ringSize == uint8ArgsList.length); require(params.ringSize == buyNoMoreThanAmountBList.length); // Validate ring-mining related arguments. for (uint i = 0; i < params.ringSize; i++) { require(uintArgsList[i][5] > 0); // "order rateAmountS is zero"); } //Check ring size require(params.ringSize > 1 && params.ringSize <= MAX_RING_SIZE); // "invalid ring size"); uint sigSize = params.ringSize << 1; require(sigSize == params.vList.length); require(sigSize == params.rList.length); require(sigSize == params.sList.length); } /// @dev assmble order parameters into Order struct. /// @return A list of orders. function assembleOrders( RingParams params, TokenTransferDelegate delegate, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private view returns (OrderState[] memory orders) { orders = new OrderState[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { uint[6] memory uintArgs = uintArgsList[i]; bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0; orders[i] = OrderState( addressList[i][0], addressList[i][1], addressList[(i + 1) % params.ringSize][1], addressList[i][2], addressList[i][3], uintArgs[2], uintArgs[3], uintArgs[0], uintArgs[1], uintArgs[4], buyNoMoreThanAmountBList[i], marginSplitAsFee, bytes32(0), uint8ArgsList[i][0], uintArgs[5], uintArgs[1], 0, // fillAmountS 0, // lrcReward 0, // lrcFee 0, // splitS 0 // splitB ); validateOrder(orders[i]); bytes32 orderHash = calculateOrderHash(orders[i]); orders[i].orderHash = orderHash; verifySignature( orders[i].owner, orderHash, params.vList[i], params.rList[i], params.sList[i] ); params.ringHash ^= orderHash; } validateOrdersCutoffs(orders, delegate); params.ringHash = keccak256( params.ringHash, params.miner, params.feeSelections ); } /// @dev validate order's parameters are OK. function validateOrder( OrderState order ) private view { require(order.owner != 0x0); // invalid order owner require(order.tokenS != 0x0); // invalid order tokenS require(order.tokenB != 0x0); // invalid order tokenB require(order.amountS != 0); // invalid order amountS require(order.amountB != 0); // invalid order amountB require(order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE); // invalid order marginSplitPercentage require(order.validSince <= block.timestamp); // order is too early to match require(order.validUntil > block.timestamp); // order is expired } function validateOrdersCutoffs(OrderState[] orders, TokenTransferDelegate delegate) private view { address[] memory owners = new address[](orders.length); bytes20[] memory tradingPairs = new bytes20[](orders.length); uint[] memory validSinceTimes = new uint[](orders.length); for (uint i = 0; i < orders.length; i++) { owners[i] = orders[i].owner; tradingPairs[i] = bytes20(orders[i].tokenS) ^ bytes20(orders[i].tokenB); validSinceTimes[i] = orders[i].validSince; } delegate.checkCutoffsBatch(owners, tradingPairs, validSinceTimes); } /// @dev Get the Keccak-256 hash of order with specified parameters. function calculateOrderHash( OrderState order ) private pure returns (bytes32) { return keccak256( delegateAddress, order.owner, order.tokenS, order.tokenB, order.wallet, order.authAddr, order.amountS, order.amountB, order.validSince, order.validUntil, order.lrcFee, order.buyNoMoreThanAmountB, order.marginSplitPercentage ); } /// @dev Verify signer's signature. function verifySignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s ) private pure { require( signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ) ); // "invalid signature"); } function getTradingPairCutoffs( address orderOwner, address token1, address token2 ) public view returns (uint) { bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); return delegate.tradingPairCutoffs(orderOwner, tokenPair); } }
@title An Implementation of LoopringProtocol. @author Daniel Wang - <[email protected]>, @author Kongliang Zhong - <[email protected]> Recognized contributing developers from the community: https://github.com/Brechtpd https://github.com/rainydio https://github.com/BenjaminPrice https://github.com/jonasshen https://github.com/Hephyrius Exchange rate (rate) is the amount to sell or sold divided by the amount to buy or bought. Rate ratio is the ratio between executed rate and an order's original rate. To require all orders' rate ratios to have coefficient ofvariation (CV) smaller than 2.5%, for an example , rateRatioCVSThreshold should be: `(0.025 * RATE_RATIO_SCALE)^2` or 62500.
contract LoopringProtocolImpl is LoopringProtocol { using AddressUtil for address; using MathUint for uint; address public constant lrcTokenAddress = 0xEF68e7C694F40c8202821eDF525dE3782458639f; address public constant tokenRegistryAddress = 0x004DeF62C71992615CF22786d0b7Efb22850Df4a; address public constant delegateAddress = 0xD22f97BCEc8E029e109412763b889fC16C4bca8B; uint64 public ringIndex = 0; uint8 public constant walletSplitPercentage = 20; uint public constant rateRatioCVSThreshold = 62500; uint public constant MAX_RING_SIZE = 16; uint public constant RATE_RATIO_SCALE = 10000; } struct OrderState { address owner; address tokenS; address tokenB; address wallet; address authAddr; uint validSince; uint validUntil; uint amountS; uint amountB; uint lrcFee; bool buyNoMoreThanAmountB; bool marginSplitAsFee; bytes32 orderHash; uint8 marginSplitPercentage; uint rateS; uint rateB; uint fillAmountS; uint lrcReward; uint lrcFeeState; uint splitS; uint splitB; } struct RingParams { uint8[] vList; bytes32[] rList; bytes32[] sList; address miner; uint16 feeSelections; } function () payable public { revert(); } function cancelOrder( address[5] addresses, uint[6] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external { uint cancelAmount = orderValues[5]; OrderState memory order = OrderState( addresses[0], addresses[1], addresses[2], addresses[3], addresses[4], orderValues[2], orderValues[3], orderValues[0], orderValues[1], orderValues[4], buyNoMoreThanAmountB, false, 0x0, marginSplitPercentage, 0, 0, 0, 0, 0, 0, 0 ); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, v, r, s ); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); delegate.addCancelled(orderHash, cancelAmount); delegate.addCancelledOrFilled(orderHash, cancelAmount); emit OrderCancelled(orderHash, cancelAmount); } function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); require(delegate.tradingPairCutoffs(msg.sender, tokenPair) < t); delegate.setTradingPairCutoffs(tokenPair, t); emit OrdersCancelled( msg.sender, token1, token2, t ); } function cancelAllOrders( uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); delegate.setCutoffs(t); emit AllOrdersCancelled(msg.sender, t); } function submitRing( address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address miner, uint16 feeSelections ) public { uint64 _ringIndex = ringIndex; ringIndex |= (1 << 63); RingParams memory params = RingParams( vList, rList, sList, miner, feeSelections, addressList.length, ); verifyInputDataIntegrity( params, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList ); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); OrderState[] memory orders = assembleOrders( params, delegate, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList ); verifyRingSignatures(params, orders); verifyTokensRegistered(params, orders); handleRing(_ringIndex, params, orders, delegate); ringIndex = _ringIndex + 1; } function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].tokenS; for (uint j = i + 1; j < ringSize; j++) { } } } function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].tokenS; for (uint j = i + 1; j < ringSize; j++) { } } } function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].tokenS; for (uint j = i + 1; j < ringSize; j++) { } } } function verifyRingSignatures( RingParams params, OrderState[] orders ) private pure { uint j; for (uint i = 0; i < params.ringSize; i++) { j = i + params.ringSize; verifySignature( orders[i].authAddr, params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } } function verifyRingSignatures( RingParams params, OrderState[] orders ) private pure { uint j; for (uint i = 0; i < params.ringSize; i++) { j = i + params.ringSize; verifySignature( orders[i].authAddr, params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } } function verifyTokensRegistered( RingParams params, OrderState[] orders ) private view { address[] memory tokens = new address[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { tokens[i] = orders[i].tokenS; } TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) } function verifyTokensRegistered( RingParams params, OrderState[] orders ) private view { address[] memory tokens = new address[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { tokens[i] = orders[i].tokenS; } TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) } require( function handleRing( uint64 _ringIndex, RingParams params, OrderState[] orders, TokenTransferDelegate delegate ) private { address _lrcTokenAddress = lrcTokenAddress; verifyRingHasNoSubRing(params.ringSize, orders); verifyMinerSuppliedFillRates(params.ringSize, orders); scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders); calculateRingFillAmount(params.ringSize, orders); calculateRingFees( delegate, params.ringSize, orders, params.miner, _lrcTokenAddress ); bytes32[] memory orderInfoList = settleRing( delegate, params.ringSize, orders, params.miner, _lrcTokenAddress ); emit RingMined( _ringIndex, params.ringHash, params.miner, orderInfoList ); } function settleRing( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private returns (bytes32[] memory orderInfoList) { orderInfoList = new bytes32[](ringSize * 7); uint p = 0; uint q = 0; uint r = 0; uint prevSplitB = orders[ringSize - 1].splitB; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; batch[p++] = bytes32(state.owner); batch[p++] = bytes32(state.tokenS); batch[p++] = bytes32(state.fillAmountS.sub(prevSplitB)); batch[p++] = bytes32(prevSplitB.add(state.splitS)); batch[p++] = bytes32(state.lrcReward); batch[p++] = bytes32(state.lrcFeeState); batch[p++] = bytes32(state.wallet); historyBatch[r++] = state.orderHash; historyBatch[r++] = bytes32( state.buyNoMoreThanAmountB ? nextFillAmountS : state.fillAmountS); orderInfoList[q++] = bytes32(state.orderHash); orderInfoList[q++] = bytes32(state.owner); orderInfoList[q++] = bytes32(state.tokenS); orderInfoList[q++] = bytes32(state.fillAmountS); orderInfoList[q++] = bytes32(state.lrcReward); orderInfoList[q++] = bytes32( state.lrcFeeState > 0 ? int(state.lrcFeeState) : -int(state.lrcReward) ); orderInfoList[q++] = bytes32( state.splitS > 0 ? int(state.splitS) : -int(state.splitB) ); prevSplitB = state.splitB; } _lrcTokenAddress, miner, walletSplitPercentage, batch ); } function settleRing( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private returns (bytes32[] memory orderInfoList) { orderInfoList = new bytes32[](ringSize * 7); uint p = 0; uint q = 0; uint r = 0; uint prevSplitB = orders[ringSize - 1].splitB; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; batch[p++] = bytes32(state.owner); batch[p++] = bytes32(state.tokenS); batch[p++] = bytes32(state.fillAmountS.sub(prevSplitB)); batch[p++] = bytes32(prevSplitB.add(state.splitS)); batch[p++] = bytes32(state.lrcReward); batch[p++] = bytes32(state.lrcFeeState); batch[p++] = bytes32(state.wallet); historyBatch[r++] = state.orderHash; historyBatch[r++] = bytes32( state.buyNoMoreThanAmountB ? nextFillAmountS : state.fillAmountS); orderInfoList[q++] = bytes32(state.orderHash); orderInfoList[q++] = bytes32(state.owner); orderInfoList[q++] = bytes32(state.tokenS); orderInfoList[q++] = bytes32(state.fillAmountS); orderInfoList[q++] = bytes32(state.lrcReward); orderInfoList[q++] = bytes32( state.lrcFeeState > 0 ? int(state.lrcFeeState) : -int(state.lrcReward) ); orderInfoList[q++] = bytes32( state.splitS > 0 ? int(state.splitS) : -int(state.splitB) ); prevSplitB = state.splitB; } _lrcTokenAddress, miner, walletSplitPercentage, batch ); } delegate.batchAddCancelledOrFilled(historyBatch); delegate.batchTransferToken( function verifyMinerSuppliedFillRates( uint ringSize, OrderState[] orders ) private pure { uint[] memory rateRatios = new uint[](ringSize); uint _rateRatioScale = RATE_RATIO_SCALE; for (uint i = 0; i < ringSize; i++) { uint s1b0 = orders[i].rateS.mul(orders[i].amountB); uint s0b1 = orders[i].amountS.mul(orders[i].rateB); rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1; } uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale); require(cvs <= rateRatioCVSThreshold); function verifyMinerSuppliedFillRates( uint ringSize, OrderState[] orders ) private pure { uint[] memory rateRatios = new uint[](ringSize); uint _rateRatioScale = RATE_RATIO_SCALE; for (uint i = 0; i < ringSize; i++) { uint s1b0 = orders[i].rateS.mul(orders[i].amountB); uint s0b1 = orders[i].amountS.mul(orders[i].rateB); rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1; } uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale); require(cvs <= rateRatioCVSThreshold); } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } } else { function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } } else { } else { function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } } else { function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } } else { function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address miner, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; state.marginSplitPercentage = _marginSplitPercentageBase; uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.owner ); if (state.tokenS == _lrcTokenAddress) { lrcSpendable = lrcSpendable.sub(state.fillAmountS); } if (state.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable.add(lrcReceiable); if (lrcTotal < state.lrcFeeState) { state.lrcFeeState = lrcTotal; state.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFeeState == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFeeState) { state.splitB = state.lrcFeeState; state.lrcFeeState = 0; state.splitB = lrcReceiable; state.lrcFeeState = state.lrcFeeState.sub(lrcReceiable); } } if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFeeState) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, miner); } if (minerLrcSpendable >= state.lrcFeeState) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.amountS ) / state.amountB).sub( state.fillAmountS ); split = nextFillAmountS.sub( state.fillAmountS.mul( state.amountB ) / state.amountS ); } if (state.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.buyNoMoreThanAmountB) { state.splitS = split; state.splitB = split; } if (split > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFeeState); state.lrcReward = state.lrcFeeState; } } state.lrcFeeState = 0; } } } function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], ); } } function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], ); } } function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], ); } } function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rateB ) / state.rateS; if (state.buyNoMoreThanAmountB) { if (fillAmountB > state.amountB) { fillAmountB = state.amountB; state.fillAmountS = fillAmountB.mul( state.rateS ) / state.rateB; require(state.fillAmountS > 0); newSmallestIdx = i; } state.lrcFeeState = state.lrcFee.mul( fillAmountB ) / state.amountB; state.lrcFeeState = state.lrcFee.mul( state.fillAmountS ) / state.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; newSmallestIdx = j; } } function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rateB ) / state.rateS; if (state.buyNoMoreThanAmountB) { if (fillAmountB > state.amountB) { fillAmountB = state.amountB; state.fillAmountS = fillAmountB.mul( state.rateS ) / state.rateB; require(state.fillAmountS > 0); newSmallestIdx = i; } state.lrcFeeState = state.lrcFee.mul( fillAmountB ) / state.amountB; state.lrcFeeState = state.lrcFee.mul( state.fillAmountS ) / state.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; newSmallestIdx = j; } } function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rateB ) / state.rateS; if (state.buyNoMoreThanAmountB) { if (fillAmountB > state.amountB) { fillAmountB = state.amountB; state.fillAmountS = fillAmountB.mul( state.rateS ) / state.rateB; require(state.fillAmountS > 0); newSmallestIdx = i; } state.lrcFeeState = state.lrcFee.mul( fillAmountB ) / state.amountB; state.lrcFeeState = state.lrcFee.mul( state.fillAmountS ) / state.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; newSmallestIdx = j; } } } else { function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rateB ) / state.rateS; if (state.buyNoMoreThanAmountB) { if (fillAmountB > state.amountB) { fillAmountB = state.amountB; state.fillAmountS = fillAmountB.mul( state.rateS ) / state.rateB; require(state.fillAmountS > 0); newSmallestIdx = i; } state.lrcFeeState = state.lrcFee.mul( fillAmountB ) / state.amountB; state.lrcFeeState = state.lrcFee.mul( state.fillAmountS ) / state.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; newSmallestIdx = j; } } } else { function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint amount; if (state.buyNoMoreThanAmountB) { amount = state.amountB.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountS = amount.mul(state.amountS) / state.amountB; state.lrcFee = amount.mul(state.lrcFee) / state.amountB; state.amountB = amount; amount = state.amountS.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountB = amount.mul(state.amountB) / state.amountS; state.lrcFee = amount.mul(state.lrcFee) / state.amountS; state.amountS = amount; } uint availableAmountS = getSpendable(delegate, state.tokenS, state.owner); state.fillAmountS = ( state.amountS < availableAmountS ? state.amountS : availableAmountS ); require(state.fillAmountS > 0); } } function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint amount; if (state.buyNoMoreThanAmountB) { amount = state.amountB.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountS = amount.mul(state.amountS) / state.amountB; state.lrcFee = amount.mul(state.lrcFee) / state.amountB; state.amountB = amount; amount = state.amountS.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountB = amount.mul(state.amountB) / state.amountS; state.lrcFee = amount.mul(state.lrcFee) / state.amountS; state.amountS = amount; } uint availableAmountS = getSpendable(delegate, state.tokenS, state.owner); state.fillAmountS = ( state.amountS < availableAmountS ? state.amountS : availableAmountS ); require(state.fillAmountS > 0); } } function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint amount; if (state.buyNoMoreThanAmountB) { amount = state.amountB.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountS = amount.mul(state.amountS) / state.amountB; state.lrcFee = amount.mul(state.lrcFee) / state.amountB; state.amountB = amount; amount = state.amountS.tolerantSub( delegate.cancelledOrFilled(state.orderHash) ); state.amountB = amount.mul(state.amountB) / state.amountS; state.lrcFee = amount.mul(state.lrcFee) / state.amountS; state.amountS = amount; } uint availableAmountS = getSpendable(delegate, state.tokenS, state.owner); state.fillAmountS = ( state.amountS < availableAmountS ? state.amountS : availableAmountS ); require(state.fillAmountS > 0); } } } else { function getSpendable( TokenTransferDelegate delegate, address tokenAddress, address tokenOwner ) private view returns (uint) { ERC20 token = ERC20(tokenAddress); uint allowance = token.allowance( tokenOwner, address(delegate) ); uint balance = token.balanceOf(tokenOwner); return (allowance < balance ? allowance : balance); } function verifyInputDataIntegrity( RingParams params, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private pure { require(params.miner != 0x0); require(params.ringSize == addressList.length); require(params.ringSize == uintArgsList.length); require(params.ringSize == uint8ArgsList.length); require(params.ringSize == buyNoMoreThanAmountBList.length); for (uint i = 0; i < params.ringSize; i++) { } require(sigSize == params.vList.length); require(sigSize == params.rList.length); require(sigSize == params.sList.length); } function verifyInputDataIntegrity( RingParams params, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private pure { require(params.miner != 0x0); require(params.ringSize == addressList.length); require(params.ringSize == uintArgsList.length); require(params.ringSize == uint8ArgsList.length); require(params.ringSize == buyNoMoreThanAmountBList.length); for (uint i = 0; i < params.ringSize; i++) { } require(sigSize == params.vList.length); require(sigSize == params.rList.length); require(sigSize == params.sList.length); } uint sigSize = params.ringSize << 1; function assembleOrders( RingParams params, TokenTransferDelegate delegate, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private view returns (OrderState[] memory orders) { orders = new OrderState[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { uint[6] memory uintArgs = uintArgsList[i]; bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0; orders[i] = OrderState( addressList[i][0], addressList[i][1], addressList[(i + 1) % params.ringSize][1], addressList[i][2], addressList[i][3], uintArgs[2], uintArgs[3], uintArgs[0], uintArgs[1], uintArgs[4], buyNoMoreThanAmountBList[i], marginSplitAsFee, bytes32(0), uint8ArgsList[i][0], uintArgs[5], uintArgs[1], ); validateOrder(orders[i]); bytes32 orderHash = calculateOrderHash(orders[i]); orders[i].orderHash = orderHash; verifySignature( orders[i].owner, orderHash, params.vList[i], params.rList[i], params.sList[i] ); params.ringHash ^= orderHash; } validateOrdersCutoffs(orders, delegate); params.ringHash = keccak256( params.ringHash, params.miner, params.feeSelections ); } function assembleOrders( RingParams params, TokenTransferDelegate delegate, address[4][] addressList, uint[6][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList ) private view returns (OrderState[] memory orders) { orders = new OrderState[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { uint[6] memory uintArgs = uintArgsList[i]; bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0; orders[i] = OrderState( addressList[i][0], addressList[i][1], addressList[(i + 1) % params.ringSize][1], addressList[i][2], addressList[i][3], uintArgs[2], uintArgs[3], uintArgs[0], uintArgs[1], uintArgs[4], buyNoMoreThanAmountBList[i], marginSplitAsFee, bytes32(0), uint8ArgsList[i][0], uintArgs[5], uintArgs[1], ); validateOrder(orders[i]); bytes32 orderHash = calculateOrderHash(orders[i]); orders[i].orderHash = orderHash; verifySignature( orders[i].owner, orderHash, params.vList[i], params.rList[i], params.sList[i] ); params.ringHash ^= orderHash; } validateOrdersCutoffs(orders, delegate); params.ringHash = keccak256( params.ringHash, params.miner, params.feeSelections ); } function validateOrder( OrderState order ) private view { require(order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE); } function validateOrdersCutoffs(OrderState[] orders, TokenTransferDelegate delegate) private view { address[] memory owners = new address[](orders.length); bytes20[] memory tradingPairs = new bytes20[](orders.length); uint[] memory validSinceTimes = new uint[](orders.length); for (uint i = 0; i < orders.length; i++) { owners[i] = orders[i].owner; tradingPairs[i] = bytes20(orders[i].tokenS) ^ bytes20(orders[i].tokenB); validSinceTimes[i] = orders[i].validSince; } delegate.checkCutoffsBatch(owners, tradingPairs, validSinceTimes); } function validateOrdersCutoffs(OrderState[] orders, TokenTransferDelegate delegate) private view { address[] memory owners = new address[](orders.length); bytes20[] memory tradingPairs = new bytes20[](orders.length); uint[] memory validSinceTimes = new uint[](orders.length); for (uint i = 0; i < orders.length; i++) { owners[i] = orders[i].owner; tradingPairs[i] = bytes20(orders[i].tokenS) ^ bytes20(orders[i].tokenB); validSinceTimes[i] = orders[i].validSince; } delegate.checkCutoffsBatch(owners, tradingPairs, validSinceTimes); } function calculateOrderHash( OrderState order ) private pure returns (bytes32) { return keccak256( delegateAddress, order.owner, order.tokenS, order.tokenB, order.wallet, order.authAddr, order.amountS, order.amountB, order.validSince, order.validUntil, order.lrcFee, order.buyNoMoreThanAmountB, order.marginSplitPercentage ); } function verifySignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s ) private pure { require( signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ) } function getTradingPairCutoffs( address orderOwner, address token1, address token2 ) public view returns (uint) { bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); return delegate.tradingPairCutoffs(orderOwner, tokenPair); } }
12,878,464
[ 1, 979, 25379, 434, 9720, 8022, 5752, 18, 225, 463, 28662, 292, 678, 539, 300, 411, 72, 28662, 292, 36, 6498, 8022, 18, 3341, 20401, 225, 1475, 932, 549, 539, 2285, 76, 932, 300, 411, 79, 932, 549, 539, 36, 6498, 8022, 18, 3341, 34, 7776, 9367, 13608, 8490, 21701, 628, 326, 19833, 30, 377, 2333, 2207, 6662, 18, 832, 19, 38, 266, 343, 6834, 72, 377, 2333, 2207, 6662, 18, 832, 19, 7596, 93, 72, 1594, 377, 2333, 2207, 6662, 18, 832, 19, 38, 275, 78, 301, 267, 5147, 377, 2333, 2207, 6662, 18, 832, 19, 78, 265, 428, 76, 275, 377, 2333, 2207, 6662, 18, 832, 19, 5256, 844, 93, 566, 407, 18903, 4993, 261, 5141, 13, 353, 326, 3844, 358, 357, 80, 578, 272, 1673, 26057, 635, 326, 3844, 358, 30143, 578, 800, 9540, 18, 13025, 7169, 353, 326, 7169, 3086, 7120, 4993, 471, 392, 1353, 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, 9720, 8022, 5752, 2828, 353, 9720, 8022, 5752, 288, 203, 565, 1450, 5267, 1304, 282, 364, 1758, 31, 203, 565, 1450, 2361, 5487, 1377, 364, 2254, 31, 203, 565, 1758, 1071, 5381, 328, 1310, 1345, 1887, 2398, 273, 374, 17432, 42, 9470, 73, 27, 39, 8148, 24, 42, 7132, 71, 11149, 3103, 28, 5340, 73, 4577, 25, 2947, 72, 41, 6418, 28, 3247, 8204, 21607, 74, 31, 203, 565, 1758, 1071, 5381, 1147, 4243, 1887, 3639, 273, 374, 92, 26565, 758, 42, 8898, 39, 11212, 2733, 5558, 3600, 8955, 3787, 27, 5292, 72, 20, 70, 27, 41, 19192, 3787, 28, 3361, 40, 74, 24, 69, 31, 203, 565, 1758, 1071, 5381, 7152, 1887, 2398, 273, 374, 17593, 3787, 74, 10580, 38, 1441, 71, 28, 41, 3103, 29, 73, 2163, 11290, 14260, 4449, 70, 5482, 29, 74, 39, 2313, 39, 24, 70, 5353, 28, 38, 31, 203, 565, 2254, 1105, 225, 1071, 225, 9221, 1016, 10402, 273, 374, 31, 203, 565, 2254, 28, 282, 1071, 5381, 9230, 5521, 16397, 4202, 273, 4200, 31, 203, 565, 2254, 565, 1071, 5381, 4993, 8541, 22007, 882, 76, 3444, 3639, 273, 1666, 2947, 713, 31, 203, 565, 2254, 565, 1071, 5381, 4552, 67, 54, 1360, 67, 4574, 4202, 273, 2872, 31, 203, 565, 2254, 565, 1071, 5381, 534, 1777, 67, 54, 789, 4294, 67, 19378, 565, 273, 12619, 31, 203, 97, 203, 565, 1958, 4347, 1119, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 1758, 1147, 55, 31, 203, 3639, 1758, 1147, 38, 31, 203, 3639, 1758, 9230, 2 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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); } // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (token/ERC20/IERC20.sol) /** * @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); } // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) // OpenZeppelin Contracts v4.4.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 * ==== */ 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); } } } } /** * @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"); } } } // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // OpenZeppelin Contracts v4.4.0 (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 Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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]{40}) is missing role (0x[0-9a-f]{64})$/ */ 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 revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // OpenZeppelin Contracts v4.4.0 (security/Pausable.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()); } } contract ECDSAOffsetRecovery { function getHashPacked( address user, uint256 amountWithFee, bytes32 originalTxHash, uint256 blockchainNum ) public pure returns (bytes32) { return keccak256(abi.encodePacked(user, amountWithFee, originalTxHash, blockchainNum)); } function toEthSignedMessageHash(bytes32 hash) public 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) ); } function ecOffsetRecover( bytes32 hash, bytes memory signature, uint256 offset ) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables with inline assembly. assembly { r := mload(add(signature, add(offset, 0x20))) s := mload(add(signature, add(offset, 0x40))) v := byte(0, mload(add(signature, add(offset, 0x60)))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } // bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // hash = keccak256(abi.encodePacked(prefix, hash)); // solium-disable-next-line arg-overflow return ecrecover(toEthSignedMessageHash(hash), v, r, s); } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } abstract contract Storage is AccessControl, Pausable, ECDSAOffsetRecovery{ bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE"); uint128 public numOfThisBlockchain; address public blockchainRouter; mapping(uint256 => bytes32) public RubicAddresses; mapping(uint256 => bool) public existingOtherBlockchain; mapping(uint256 => uint256) public feeAmountOfBlockchain; mapping(uint256 => uint256) public blockchainCryptoFee; uint256 public constant SIGNATURE_LENGTH = 65; mapping(bytes32 => uint256) public processedTransactions; uint256 public minConfirmationSignatures = 3; uint256 public minTokenAmount; uint256 public maxTokenAmount; uint256 public maxGasPrice; uint256 public minConfirmationBlocks; uint256 public refundSlippage; uint256 public accTokenFee = 1; } abstract contract MainBase is Storage{ using Address for address payable; using SafeERC20 for IERC20; bytes32 internal constant IMPLEMENTATION_MAPPING_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; struct Implementation{ address router; address _address; } /** * @dev throws if transaction sender is not in owner role */ modifier onlyOwner() { require( hasRole(OWNER_ROLE, _msgSender()), "Caller is not in owner role" ); _; } /** * @dev throws if transaction sender is not in owner or manager role */ modifier onlyOwnerAndManager() { require( hasRole(OWNER_ROLE, _msgSender()) || hasRole(MANAGER_ROLE, _msgSender()), "Caller is not in owner or manager role" ); _; } /** * @dev throws if transaction sender is not in relayer role */ modifier onlyRelayer() { require( hasRole(RELAYER_ROLE, _msgSender()), "swapContract: Caller is not in relayer role" ); _; } modifier onlyOwnerAndManagerAndRelayer(){ require( hasRole(OWNER_ROLE, _msgSender()) || hasRole(MANAGER_ROLE, _msgSender()) || hasRole(RELAYER_ROLE, _msgSender()), "swapContract: not ownr mngr rlyr" ); _; } function getOtherBlockchainAvailableByNum(uint256 blockchain) external view returns (bool) { return existingOtherBlockchain[blockchain]; } /** * @dev Registers another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function addOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( numOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( !existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[numOfOtherBlockchain] = true; } /** * @dev Unregisters another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function removeOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain was not added" ); existingOtherBlockchain[numOfOtherBlockchain] = false; } /** * @dev Change existing blockchain id * @param oldNumOfOtherBlockchain number of existing blockchain * @param newNumOfOtherBlockchain number of new blockchain */ function changeOtherBlockchain( uint128 oldNumOfOtherBlockchain, uint128 newNumOfOtherBlockchain ) external onlyOwner { require( oldNumOfOtherBlockchain != newNumOfOtherBlockchain, "swapContract: Cannot change blockchains with same number" ); require( newNumOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( existingOtherBlockchain[oldNumOfOtherBlockchain], "swapContract: This blockchain was not added" ); require( !existingOtherBlockchain[newNumOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[oldNumOfOtherBlockchain] = false; existingOtherBlockchain[newNumOfOtherBlockchain] = true; } // FEE MANAGEMENT /** * @dev Sends collected crypto fee to the owner */ function collectCryptoFee(address toAddress) external onlyOwner { require(isRelayer(toAddress), 'swapContract: fee can be sent only to a relayer'); payable(toAddress).sendValue(address(this).balance); } /** * @dev Sends collected token fee to the owner */ function collectTokenFee() external onlyOwner { IERC20 _Rubic = IERC20(address(uint160(uint256(RubicAddresses[numOfThisBlockchain])))); _Rubic.safeTransfer( msg.sender, accTokenFee - 1 ); accTokenFee = 1; //GAS savings } /** * @dev Changes fee values for blockchains in feeAmountOfBlockchain variables * @notice fee is represented as hundredths of a bip, i.e. 1e-6 * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount to substruct from transfer amount */ function setFeeAmountOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManager { feeAmountOfBlockchain[_blockchainNum] = feeAmount; } /** * @dev Changes crypto fee values for blockchains in blockchainCryptoFee variables * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount that must be sent calling transferToOtherBlockchain */ function setCryptoFeeOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManagerAndRelayer { blockchainCryptoFee[_blockchainNum] = feeAmount; } /** * @dev Changes the address of Rubic in the certain blockchain * @param _blockchainNum Existing number of blockchain * @param _RubicAddress The Rubic address */ function setRubicAddressOfBlockchain( uint128 _blockchainNum, bytes32 _RubicAddress ) external onlyOwnerAndManager { RubicAddresses[_blockchainNum] = _RubicAddress; } /** * @dev Approves tokens to a swap Router. We can approve the most popular tokens before any swaps * To spare users from paying for it * @param _token The token address to approve */ function approveTokenToRouter(IERC20 _token, address _router) external onlyOwnerAndManager{ _token.approve(_router, type(uint256).max); } /** * @dev With this function owner, which is a multisig account, can withdraw some RBC from the pool * @param amount The amount to withdraw */ function poolBalancing(uint256 amount) external onlyOwner{ IERC20(address(uint160(uint256(RubicAddresses[numOfThisBlockchain])))).transfer(msg.sender, amount); } // VALIDATOR CONFIRMATIONS MANAGEMENT /** * @dev Changes requirement for minimal amount of signatures to validate on transfer * @param _minConfirmationSignatures Number of signatures to verify */ function setMinConfirmationSignatures(uint256 _minConfirmationSignatures) external onlyOwner { require( _minConfirmationSignatures > 0, "swapContract: At least 1 confirmation can be set" ); minConfirmationSignatures = _minConfirmationSignatures; } /** * @dev Changes requirement for minimal token amount on transfers * @param _minTokenAmount Amount of tokens */ function setMinTokenAmount(uint256 _minTokenAmount) external onlyOwnerAndManager { minTokenAmount = _minTokenAmount; } /** * @dev Changes requirement for maximum token amount on transfers * @param _maxTokenAmount Amount of tokens */ function setMaxTokenAmount(uint256 _maxTokenAmount) external onlyOwnerAndManager { maxTokenAmount = _maxTokenAmount; } /** * @dev Changes parameter of maximum gas price on which relayer nodes will operate * @param _maxGasPrice Price of gas in wei */ function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwnerAndManager { require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); maxGasPrice = _maxGasPrice; } /** * @dev Changes requirement for minimal amount of block to consider tx confirmed on validator * @param _minConfirmationBlocks Amount of blocks */ function setMinConfirmationBlocks(uint256 _minConfirmationBlocks) external onlyOwnerAndManager { minConfirmationBlocks = _minConfirmationBlocks; } function setRefundSlippage(uint256 _refundSlippage) external onlyOwnerAndManager { refundSlippage = _refundSlippage; } /** * @dev Transfers permissions of contract ownership. * Will setup new owner and one manager on contract. * Main purpose of this function is to transfer ownership from deployer account ot real owner * @param newOwner Address of new owner * @param newManager Address of new manager */ function transferOwnerAndSetManager(address newOwner, address newManager) external onlyOwner { require( newOwner != _msgSender(), "swapContract: New owner must be different than current" ); require( newOwner != address(0x0), "swapContract: Owner cannot be zero address" ); require( newManager != address(0x0), "swapContract: Owner cannot be zero address" ); _setupRole(DEFAULT_ADMIN_ROLE, newOwner); _setupRole(OWNER_ROLE, newOwner); _setupRole(MANAGER_ROLE, newManager); renounceRole(OWNER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Pauses transfers of tokens on contract */ function pauseExecution() external onlyOwner { _pause(); } /** * @dev Resumes transfers of tokens on contract */ function continueExecution() external onlyOwner { _unpause(); } /** * @dev Function to check if address is belongs to owner role * @param account Address to check */ function isOwner(address account) public view returns (bool) { return hasRole(OWNER_ROLE, account); } /** * @dev Function to check if address is belongs to manager role * @param account Address to check */ function isManager(address account) public view returns (bool) { return hasRole(MANAGER_ROLE, account); } /** * @dev Function to check if address is belongs to relayer role * @param account Address to check */ function isRelayer(address account) public view returns (bool) { return hasRole(RELAYER_ROLE, account); } /** * @dev Function to check if address is belongs to validator role * @param account Address to check * */ function isValidator(address account) public view returns (bool) { return hasRole(VALIDATOR_ROLE, account); } /** * @dev Function changes values associated with certain originalTxHash * @param originalTxHash Transaction hash to change * @param statusCode Associated status: 0-Not processed, 1-Processed, 2-Reverted */ function changeTxStatus( bytes32 originalTxHash, uint256 statusCode ) external onlyRelayer { require( statusCode != 0, "swapContract: you cannot set the statusCode to 0" ); require( processedTransactions[originalTxHash] != 1, "swapContract: transaction with this originalTxHash has already been set as succeed" ); processedTransactions[originalTxHash] = statusCode; } /** * @dev Plain fallback function to receive crypto */ receive() external payable {} } contract MainContract is MainBase{ constructor( uint128 _numOfThisBlockchain, uint128[] memory _numsOfOtherBlockchains, uint256[] memory tokenLimits, uint256 _maxGasPrice, uint256 _minConfirmationBlocks, uint256 _refundSlippage, bytes32[] memory _RubicAddresses ) { for (uint256 i = 0; i < _numsOfOtherBlockchains.length; i++) { require( _numsOfOtherBlockchains[i] != _numOfThisBlockchain, "swapContract: Number of this blockchain is in array of other blockchains" ); existingOtherBlockchain[_numsOfOtherBlockchains[i]] = true; } for (uint256 i = 0; i < _RubicAddresses.length; i++) { RubicAddresses[i + 1] = _RubicAddresses[i]; } require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); numOfThisBlockchain = _numOfThisBlockchain; minTokenAmount = tokenLimits[0]; maxTokenAmount = tokenLimits[1]; maxGasPrice = _maxGasPrice; refundSlippage = _refundSlippage; minConfirmationBlocks = _minConfirmationBlocks; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OWNER_ROLE, _msgSender()); } function getStorageValue(bytes4 sig, bytes32 slot) internal view returns (Implementation storage impl) { assembly { // Store num in memory scratch space (note: lookup "free memory pointer" if you need to allocate space) mstore(0, sig) // Store slot number in scratch space after num mstore(32, slot) // Create hash from previously stored num and slot let hash := keccak256(0, 64) // Load mapping value using the just calculated hash impl.slot := hash } } function getInfoAboutSig(bytes4 sig, bytes32 slot) external view returns( address implementationAddress, address router ){ Implementation storage impl; assembly { // Store num in memory scratch space (note: lookup "free memory pointer" if you need to allocate space) mstore(0, sig) // Store slot number in scratch space after num mstore(32, slot) // Create hash from previously stored num and slot let hash := keccak256(0, 64) // Load mapping value using the just calculated hash impl.slot := hash } implementationAddress = impl._address; router = impl.router; } function addInstance( bytes4 sig, address _address, address _router ) external onlyOwner{ Implementation storage impl = getStorageValue(sig, IMPLEMENTATION_MAPPING_SLOT); impl._address = _address; impl.router = _router; IERC20(address(uint160(uint256(RubicAddresses[numOfThisBlockchain])))).approve( _router, type(uint256).max ); } function setRouter(bytes4 sig, address _router) external onlyOwnerAndManager{ require(_router != address(0), 'router cannot be zero'); Implementation storage impl = getStorageValue(sig, IMPLEMENTATION_MAPPING_SLOT); impl.router = _router; IERC20(address(uint160(uint256(RubicAddresses[numOfThisBlockchain])))).approve( _router, type(uint256).max ); } fallback() external payable{ Implementation storage impl = getStorageValue(msg.sig, IMPLEMENTATION_MAPPING_SLOT); address implementation = impl._address; blockchainRouter = impl.router; require(blockchainRouter != address(0), 'no instanceaAbb'); 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 Approves tokens to a swap Router. We can approve the most popular tokens before any swaps To spare users from paying for it @param _token The token address to approve/
function approveTokenToRouter(IERC20 _token, address _router) external onlyOwnerAndManager{ _token.approve(_router, type(uint256).max); }
2,531,599
[ 1, 12053, 3324, 2430, 358, 279, 7720, 9703, 18, 1660, 848, 6617, 537, 326, 4486, 1843, 2490, 2430, 1865, 1281, 1352, 6679, 2974, 1694, 834, 3677, 628, 8843, 310, 364, 518, 225, 389, 2316, 1021, 1147, 1758, 358, 6617, 537, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6617, 537, 1345, 774, 8259, 12, 45, 654, 39, 3462, 389, 2316, 16, 1758, 389, 10717, 13, 3903, 1338, 5541, 1876, 1318, 95, 203, 3639, 389, 2316, 18, 12908, 537, 24899, 10717, 16, 618, 12, 11890, 5034, 2934, 1896, 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 ]
./full_match/3/0x40C536F5A70968007eb95bC0ceE7610734187734/sources/contracts/LEARNToken.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract LEARNToken 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 = "LT"; name = "LEARNToken"; decimals = 0; _totalSupply = 100000000; balances[0x691f5C83895939Fa97455cc64a443c391bfB4e44] = _totalSupply; emit Transfer(address(0), 0x691f5C83895939Fa97455cc64a443c391bfB4e44, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override 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 override 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 override 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 override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
14,153,151
[ 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, 5380, 4391, 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, 12050, 14432, 203, 3639, 508, 273, 315, 900, 4391, 1345, 14432, 203, 3639, 15105, 273, 374, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 8148, 21, 74, 25, 39, 10261, 6675, 6162, 5520, 29634, 29, 5608, 2539, 952, 1105, 69, 6334, 23, 71, 5520, 21, 17156, 38, 24, 73, 6334, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 8148, 21, 74, 25, 39, 10261, 6675, 6162, 5520, 29634, 29, 5608, 2539, 952, 1105, 69, 6334, 23, 71, 5520, 21, 17156, 38, 24, 73, 6334, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 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, 3849, 1476, 1135, 261, 11890, 11013, 13, 288, 2 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; /// @title A contract that stores fees for later withdrawal contract FeeBankContract { /// @notice The event emitted whenever ETH is deposited. /// @param depositor The address of the account making the deposit. /// @param receiver The address of the account eligible for withdrawal. /// @param amount The newly deposited amount. /// @param totalAmount The total amount the receiver can withdraw, including the new deposit. event DepositEvent( address depositor, address receiver, uint64 amount, uint64 totalAmount ); /// @notice The event emitted whenever ETH is withdrawn. /// @param sender The address of the account that triggered the withdrawal. /// @param receiver The address of the account to which the ETH is sent. /// @param amount The withdrawn amount. /// @param totalAmount The remaining deposit. event WithdrawEvent( address sender, address receiver, uint64 amount, uint64 totalAmount ); mapping(address => uint64) public deposits; /// @notice Deposit ETH for later withdrawal /// @param receiver Address of the account that is eligible for withdrawal. function deposit(address receiver) external payable { require(receiver != address(0), "FeeBank: receiver is zero address"); require(msg.value > 0, "FeeBank: fee is zero"); require( msg.value <= type(uint64).max - deposits[receiver], "FeeBank: balance would exceed uint64" ); deposits[receiver] += uint64(msg.value); emit DepositEvent( msg.sender, receiver, uint64(msg.value), deposits[receiver] ); } /// @notice Withdraw ETH previously deposited in favor of the caller. /// @param receiver The address to which the ETH will be sent. /// @param amount The amount to withdraw (must not be greater than the deposited amount) function withdraw(address receiver, uint64 amount) external { _withdraw(receiver, amount); } /// @notice Withdraw all ETH previously deposited in favor of the caller and send it to them. function withdraw() external { _withdraw(msg.sender, deposits[msg.sender]); } function _withdraw(address receiver, uint64 amount) internal { require(receiver != address(0), "FeeBank: receiver is zero address"); uint64 depositBefore = deposits[msg.sender]; require(depositBefore > 0, "FeeBank: deposit is empty"); require(amount <= depositBefore, "FeeBank: amount exceeds deposit"); deposits[msg.sender] = depositBefore - amount; (bool success, ) = receiver.call{value: amount}(""); require(success, "FeeBank: withdrawal call failed"); emit WithdrawEvent(msg.sender, receiver, amount, deposits[msg.sender]); } }
@notice Withdraw all ETH previously deposited in favor of the caller and send it to them.
function withdraw() external { _withdraw(msg.sender, deposits[msg.sender]); }
6,444,211
[ 1, 1190, 9446, 777, 512, 2455, 7243, 443, 1724, 329, 316, 18552, 434, 326, 4894, 471, 1366, 518, 358, 2182, 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 ]
[ 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, 565, 445, 598, 9446, 1435, 3903, 288, 203, 3639, 389, 1918, 9446, 12, 3576, 18, 15330, 16, 443, 917, 1282, 63, 3576, 18, 15330, 19226, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:ВЗОРВАТЬСЯ{},
5,484,059
[ 1, 145, 99, 145, 125, 145, 118, 146, 227, 146, 229, 145, 126, 145, 121, 145, 123, 225, 145, 115, 145, 120, 145, 127, 146, 227, 145, 115, 145, 113, 145, 124, 146, 228, 146, 242, 225, 145, 126, 145, 113, 225, 145, 128, 146, 227, 145, 118, 145, 117, 145, 115, 146, 238, 145, 114, 145, 127, 146, 227, 145, 126, 145, 127, 145, 125, 225, 145, 125, 145, 121, 146, 229, 145, 121, 145, 126, 145, 116, 145, 118, 225, 145, 115, 225, 145, 258, 145, 113, 145, 123, 145, 121, 146, 228, 146, 229, 145, 113, 145, 126, 145, 118, 261, 145, 245, 145, 250, 145, 257, 145, 259, 145, 245, 145, 243, 145, 100, 145, 110, 145, 99, 145, 112, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 245, 145, 250, 145, 257, 145, 259, 145, 245, 145, 243, 145, 100, 145, 110, 145, 99, 145, 112, 2916, 16, 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 ]
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.7; import "../../lib/AddressUtil.sol"; import "../../lib/BurnableERC20.sol"; import "../../lib/ERC20SafeTransfer.sol"; import "./ExchangeAccounts.sol"; import "./ExchangeBalances.sol"; import "./ExchangeData.sol"; import "./ExchangeMode.sol"; import "./ExchangeTokens.sol"; /// @title ExchangeWithdrawals. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeWithdrawals { using AddressUtil for address; using AddressUtil for address payable; using MathUint for uint; using ERC20SafeTransfer for address; using ExchangeAccounts for ExchangeData.State; using ExchangeBalances for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; event BlockFeeWithdrawn( uint indexed blockIdx, uint amount ); event WithdrawalRequested( uint indexed withdrawalIdx, uint24 indexed accountID, uint16 indexed tokenID, uint96 amount ); event WithdrawalCompleted( uint24 indexed accountID, uint16 indexed tokenID, address to, uint96 amount ); event WithdrawalFailed( uint24 indexed accountID, uint16 indexed tokenID, address to, uint96 amount ); function getNumWithdrawalRequestsProcessed( ExchangeData.State storage S ) public view returns (uint) { ExchangeData.Block storage currentBlock = S.blocks[S.blocks.length - 1]; return currentBlock.numWithdrawalRequestsCommitted; } function getNumAvailableWithdrawalSlots( ExchangeData.State storage S ) public view returns (uint) { uint numOpenRequests = S.withdrawalChain.length - getNumWithdrawalRequestsProcessed(S); return ExchangeData.MAX_OPEN_WITHDRAWAL_REQUESTS() - numOpenRequests; } function getWithdrawRequest( ExchangeData.State storage S, uint index ) public view returns ( bytes32 accumulatedHash, uint256 accumulatedFee, uint32 timestamp ) { require(index < S.withdrawalChain.length, "INVALID_INDEX"); ExchangeData.Request storage request = S.withdrawalChain[index]; accumulatedHash = request.accumulatedHash; accumulatedFee = request.accumulatedFee; timestamp = request.timestamp; } function withdraw( ExchangeData.State storage S, uint24 accountID, address token, uint96 amount ) internal { require(amount > 0, "ZERO_VALUE"); require(!S.isInWithdrawalMode(), "INVALID_MODE"); require(S.areUserRequestsEnabled(), "USER_REQUEST_SUSPENDED"); require(getNumAvailableWithdrawalSlots(S) > 0, "TOO_MANY_REQUESTS_OPEN"); uint16 tokenID = S.getTokenID(token); // Check ETH value sent, can be larger than the expected withdraw fee require(msg.value >= S.withdrawalFeeETH, "INSUFFICIENT_FEE"); // Send surplus of ETH back to the sender msg.sender.transferETH(msg.value.sub(S.withdrawalFeeETH), gasleft()); // Add the withdraw to the withdraw chain ExchangeData.Request storage prevRequest = S.withdrawalChain[S.withdrawalChain.length - 1]; ExchangeData.Request memory request = ExchangeData.Request( sha256( abi.encodePacked( prevRequest.accumulatedHash, accountID, uint8(tokenID), amount ) ), prevRequest.accumulatedFee.add(S.withdrawalFeeETH), uint32(now) ); S.withdrawalChain.push(request); emit WithdrawalRequested( uint32(S.withdrawalChain.length - 1), accountID, tokenID, amount ); } // We still alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTreeFor( ExchangeData.State storage S, address owner, address token, uint pubKeyX, uint pubKeyY, uint32 nonce, uint96 balance, uint256 tradeHistoryRoot, uint256[20] memory accountMerkleProof, uint256[8] memory balanceMerkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); ExchangeData.Block storage lastFinalizedBlock = S.blocks[S.numBlocksFinalized - 1]; uint24 accountID = S.getAccountID(owner); uint16 tokenID = S.getTokenID(token); require(S.withdrawnInWithdrawMode[owner][token] == false, "WITHDRAWN_ALREADY"); ExchangeBalances.verifyAccountBalance( uint256(lastFinalizedBlock.merkleRoot), accountID, tokenID, pubKeyX, pubKeyY, nonce, balance, tradeHistoryRoot, accountMerkleProof, balanceMerkleProof ); // Make sure the balance can only be withdrawn once S.withdrawnInWithdrawMode[owner][token] = true; // Transfer the tokens transferTokens( S, accountID, tokenID, balance, false ); } function withdrawFromDepositRequest( ExchangeData.State storage S, uint depositIdx ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); ExchangeData.Block storage lastFinalizedBlock = S.blocks[S.numBlocksFinalized - 1]; require(depositIdx >= lastFinalizedBlock.numDepositRequestsCommitted, "REQUEST_INCLUDED_IN_FINALIZED_BLOCK"); // The deposit info is stored at depositIdx - 1 ExchangeData.Deposit storage _deposit = S.deposits[depositIdx.sub(1)]; uint amount = _deposit.amount; require(amount > 0, "WITHDRAWN_ALREADY"); // Set the amount to 0 so it cannot be withdrawn again _deposit.amount = 0; // Transfer the tokens transferTokens( S, _deposit.accountID, _deposit.tokenID, amount, false ); } function withdrawFromApprovedWithdrawal( ExchangeData.State storage S, uint blockIdx, ExchangeData.Block storage withdrawBlock, uint slotIdx, bool allowFailure ) public returns (bool success) { require(slotIdx < withdrawBlock.blockSize, "INVALID_SLOT_IDX"); // Only allow withdrawing on finalized blocks require(blockIdx < S.numBlocksFinalized, "BLOCK_NOT_FINALIZED"); // Get the withdrawal data from storage for the given slot uint[] memory slice = new uint[](2); uint slot = (7 * slotIdx) / 32; uint offset = (7 * (slotIdx + 1)) - (slot * 32); uint sc = 0; uint data = 0; // Short byte arrays (length <= 31) are stored differently in storage if (withdrawBlock.withdrawals.length >= 32) { bytes storage withdrawals = withdrawBlock.withdrawals; uint dataSlot1 = 0; uint dataSlot2 = 0; assembly { // keccak hash to get the contents of the array mstore(0x0, withdrawals_slot) sc := keccak256(0x0, 0x20) dataSlot1 := sload(add(sc, slot)) dataSlot2 := sload(add(sc, add(slot, 1))) } // Stitch the data together so we can extract the data in a single uint // (withdrawal data is at the LSBs) slice[0] = dataSlot1; slice[1] = dataSlot2; assembly { data := mload(add(slice, offset)) } } else { bytes memory mWithdrawals = withdrawBlock.withdrawals; assembly { data := mload(add(mWithdrawals, offset)) } } // Extract the withdrawal data uint16 tokenID = uint16((data >> 48) & 0xFF); uint24 accountID = uint24((data >> 28) & 0xFFFFF); uint amount = (data & 0xFFFFFFF).decodeFloat(); // Transfer the tokens success = transferTokens( S, accountID, tokenID, amount, allowFailure ); if (success && amount > 0) { // Set everything to 0 for this withdrawal so it cannot be used anymore data = data & uint(~((1 << (7 * 8)) - 1)); // Update the data in storage if (withdrawBlock.withdrawals.length >= 32) { assembly { mstore(add(slice, offset), data) } uint dataSlot1 = slice[0]; uint dataSlot2 = slice[1]; assembly { sstore(add(sc, slot), dataSlot1) sstore(add(sc, add(slot, 1)), dataSlot2) } } else { bytes memory mWithdrawals = withdrawBlock.withdrawals; assembly { mstore(add(mWithdrawals, offset), data) } withdrawBlock.withdrawals = mWithdrawals; } } } function withdrawBlockFee( ExchangeData.State storage S, uint blockIdx, address payable feeRecipient ) public returns (uint feeAmountToOperator) { require(blockIdx > 0 && blockIdx < S.blocks.length, "INVALID_BLOCK_IDX"); ExchangeData.Block storage requestedBlock = S.blocks[blockIdx]; ExchangeData.Block storage previousBlock = S.blocks[blockIdx - 1]; require(blockIdx < S.numBlocksFinalized, "BLOCK_NOT_FINALIZED"); require(requestedBlock.blockFeeWithdrawn == false, "FEE_WITHDRAWN_ALREADY"); uint feeAmount = 0; uint32 lastRequestTimestamp = 0; { uint startIndex = previousBlock.numDepositRequestsCommitted; uint endIndex = requestedBlock.numDepositRequestsCommitted; if(endIndex > startIndex) { feeAmount = S.depositChain[endIndex - 1].accumulatedFee.sub( S.depositChain[startIndex - 1].accumulatedFee ); lastRequestTimestamp = S.depositChain[endIndex - 1].timestamp; } else { startIndex = previousBlock.numWithdrawalRequestsCommitted; endIndex = requestedBlock.numWithdrawalRequestsCommitted; if(endIndex > startIndex) { feeAmount = S.withdrawalChain[endIndex - 1].accumulatedFee.sub( S.withdrawalChain[startIndex - 1].accumulatedFee ); lastRequestTimestamp = S.withdrawalChain[endIndex - 1].timestamp; } else { revert("BLOCK_HAS_NO_OPERATOR_FEE"); } } } // Calculate how much of the fee the operator gets for the block // If there are many requests than lastRequestTimestamp ~= firstRequestTimestamp so // all requests will need to be done in FEE_BLOCK_FINE_START_TIME minutes to get the complete fee. // If there are very few requests than lastRequestTimestamp >> firstRequestTimestamp and we don't want // to fine the operator for waiting until he can fill a complete block. // This is why we use the timestamp of the last request included in the block. uint32 blockTimestamp = requestedBlock.timestamp; uint32 startTime = lastRequestTimestamp + ExchangeData.FEE_BLOCK_FINE_START_TIME(); uint fine = 0; if (blockTimestamp > startTime) { fine = feeAmount.mul(blockTimestamp - startTime) / ExchangeData.FEE_BLOCK_FINE_MAX_DURATION(); } uint feeAmountToBurn = (fine > feeAmount) ? feeAmount : fine; feeAmountToOperator = feeAmount - feeAmountToBurn; // Make sure it can't be withdrawn again requestedBlock.blockFeeWithdrawn = true; // Burn part of the fee by sending it to the protocol fee manager S.loopring.protocolFeeVault().transferETH(feeAmountToBurn, gasleft()); // Transfer the fee to the operator feeRecipient.transferETH(feeAmountToOperator, gasleft()); emit BlockFeeWithdrawn(blockIdx, feeAmount); } function distributeWithdrawals( ExchangeData.State storage S, uint blockIdx, uint maxNumWithdrawals ) public { require(blockIdx < S.blocks.length, "INVALID_BLOCK_IDX"); require(maxNumWithdrawals > 0, "INVALID_MAX_NUM_WITHDRAWALS"); ExchangeData.Block storage withdrawBlock = S.blocks[blockIdx]; // Check if this is a withdrawal block require( withdrawBlock.blockType == ExchangeData.BlockType.ONCHAIN_WITHDRAWAL || withdrawBlock.blockType == ExchangeData.BlockType.OFFCHAIN_WITHDRAWAL, "INVALID_BLOCK_TYPE" ); // Only allow withdrawing on finalized blocks require(blockIdx < S.numBlocksFinalized, "BLOCK_NOT_FINALIZED"); // Check if the withdrawals were already completely distributed require(withdrawBlock.numWithdrawalsDistributed < withdrawBlock.blockSize, "WITHDRAWALS_ALREADY_DISTRIBUTED"); // Only allow the operator to distibute withdrawals at first, if he doesn't do it in time // anyone can do it and get paid a part of the exchange stake bool bOnlyOperator = now < withdrawBlock.timestamp + ExchangeData.MAX_TIME_TO_DISTRIBUTE_WITHDRAWALS(); if (bOnlyOperator) { require(msg.sender == S.operator, "UNAUTHORIZED"); } // Calculate the range of withdrawals we'll do uint start = withdrawBlock.numWithdrawalsDistributed; uint end = start.add(maxNumWithdrawals); if (end > withdrawBlock.blockSize) { end = withdrawBlock.blockSize; } // Do the withdrawals uint gasLimit = ExchangeData.MIN_GAS_TO_DISTRIBUTE_WITHDRAWALS(); uint totalNumWithdrawn = start; while (totalNumWithdrawn < end && gasleft() >= gasLimit) { // Don't check the return value here, the withdrawal is allowed to fail. // The automatic token disribution by the operator is a best effort only. // The account owner can always manually withdraw without any limits. withdrawFromApprovedWithdrawal( S, blockIdx, withdrawBlock, totalNumWithdrawn, true ); totalNumWithdrawn++; } withdrawBlock.numWithdrawalsDistributed = uint16(totalNumWithdrawn); // Fine the exchange if the withdrawals are done too late if (!bOnlyOperator) { // We use the stake of the exchange to punish withdrawals that are distributed too late uint numWithdrawn = totalNumWithdrawn.sub(start); uint totalFine = S.loopring.withdrawalFineLRC().mul(numWithdrawn); // Burn 50% of the fine, reward the distributer the rest uint amountToBurn = totalFine / 2; uint amountToDistributer = totalFine - amountToBurn; S.loopring.burnExchangeStake(S.id, amountToBurn); S.loopring.withdrawExchangeStake(S.id, msg.sender, amountToDistributer); } } // == Internal Functions == // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than GAS_LIMIT_SEND_TOKENS gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferTokens( ExchangeData.State storage S, uint24 accountID, uint16 tokenID, uint amount, bool allowFailure ) internal returns (bool success) { // If we're withdrawing from the protocol fee account send the tokens // directly to the protocol fee vault. // If we're withdrawing to an unknown account (can currently happen while // distributing tokens in shutdown) send the tokens to the protocol fee vault as well. address to; if (accountID == 0 || accountID >= S.accounts.length) { to = S.loopring.protocolFeeVault(); } else { to = S.accounts[accountID].owner; } address token = S.getTokenAddress(tokenID); // Either limit the gas by ExchangeData.GAS_LIMIT_SEND_TOKENS() or forward all gas uint gasLimit = allowFailure ? ExchangeData.GAS_LIMIT_SEND_TOKENS() : gasleft(); // Transfer the tokens from the contract to the owner if (amount > 0) { if (token == address(0)) { // ETH success = to.sendETH(amount, gasLimit); } else { // ERC20 token success = token.safeTransferWithGasLimit(to, amount, gasLimit); } } else { success = true; } if (!allowFailure) { require(success, "TRANSFER_FAILURE"); } // Emit event if (!success) { emit WithdrawalFailed( accountID, tokenID, to, uint96(amount) ); } else if(accountID > 0 || tokenID > 0 || amount > 0) { // Only emit an event when the withdrawal data hasn't been reset yet // by a previous successful withdrawal emit WithdrawalCompleted( accountID, tokenID, to, uint96(amount) ); } } }
Make sure it can't be withdrawn again
requestedBlock.blockFeeWithdrawn = true;
2,477,366
[ 1, 6464, 3071, 518, 848, 1404, 506, 598, 9446, 82, 3382, 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, 3639, 3764, 1768, 18, 2629, 14667, 1190, 9446, 82, 273, 638, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-08-16 */ // Sources flattened with hardhat v2.6.0 https://hardhat.org // File @openzeppelin/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/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/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 operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/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/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; 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 @openzeppelin/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) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] 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/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/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}. 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 {} } // File @openzeppelin/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/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ 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; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev 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(IAccessControl).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()); } } } // File @openzeppelin/contracts/utils/structs/[email protected] 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/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // File @openzeppelin/contracts/utils/[email protected] 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/token/ERC721/presets/[email protected] pragma solidity ^0.8.0; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721PresetMinterPauserAutoId is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; string private _baseTokenURI; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol, string memory baseTokenURI ) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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 NftGift.sol pragma solidity ^0.8.6; contract PPGift is ERC721PresetMinterPauserAutoId{ string private _baseTokenURI; constructor(string memory name, string memory symbol, string memory baseTokenURI)ERC721PresetMinterPauserAutoId(name, symbol, baseTokenURI){ _baseTokenURI = baseTokenURI; } bool private uriFrozen = false; uint private maxPerTx = 10; modifier onlyAdmin{ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "onlyAdmin: Unauthorized"); _; } modifier onlyAdminOrMinter{ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || hasRole(MINTER_ROLE, _msgSender()) , "onlyAdminOrMinter: Unauthorized"); _; } modifier noContract{ require(tx.origin==msg.sender, "noContract: Only EOA"); _; } function setBaseURI(string memory newURI) onlyAdmin public { require(uriFrozen==false, "setTokenURI: URI has been frozen"); _baseTokenURI = newURI; } function _baseURI() internal view override returns (string memory){ return _baseTokenURI; } function burn(uint tokenId) public virtual override onlyAdminOrMinter { //Disables burn revert("burn: Burn disabled"); } function mint(address to) public virtual override onlyAdminOrMinter{ //mints gift //+1 used to avoid id 0 _safeMint(to, totalSupply()+1); } function mintMulti(uint count, address to) public onlyAdminOrMinter{ //mints multiple tokens to 1 address for(uint i=0; i<count; i++){ _safeMint(to, totalSupply()+1); } } function mintMultiAddress(address[] memory addressList) public onlyAdminOrMinter{ //mints 1 token to every input address for(uint i=0; i<addressList.length; i++){ _safeMint(addressList[i], totalSupply()+1); } } function withdrawEth() external onlyAdmin{ require(address(this).balance>0, "Insufficient balance"); payable(msg.sender).transfer(address(this).balance); } function withdrawToken(IERC20 tokenAddress) external onlyAdmin{ tokenAddress.transfer(msg.sender, tokenAddress.balanceOf(address(this))); } }
mints 1 token to every input address
function mintMultiAddress(address[] memory addressList) public onlyAdminOrMinter{ for(uint i=0; i<addressList.length; i++){ _safeMint(addressList[i], totalSupply()+1); } }
10,498,190
[ 1, 81, 28142, 404, 1147, 358, 3614, 810, 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, 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, 312, 474, 5002, 1887, 12, 2867, 8526, 3778, 1758, 682, 13, 1071, 1338, 4446, 1162, 49, 2761, 95, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 277, 32, 2867, 682, 18, 2469, 31, 277, 27245, 95, 203, 5411, 389, 4626, 49, 474, 12, 2867, 682, 63, 77, 6487, 2078, 3088, 1283, 1435, 15, 21, 1769, 203, 3639, 289, 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 ]
./full_match/80001/0x7daB91C59c414e37e002AB4dab53cA0754733ab6/sources/contracts/v1/SwylClub.sol
* @notice Lets a Club's owner delete a Tier @param _tierId uint256 - the uid of the tier to be deleted/ CANNOT delete a Tier if there are still members in it get target Tier array validate if `_param.tierId` points to a valid Tier shift items toward to cover the target deleted tier => eventually create a duplicating on the last item
function deleteTier(uint256 _clubId, uint256 _tierId) external override onlyClubOwner(_clubId) onlyClubOwnerRole() onlyExistingClub(_clubId) { require(getSubscriptionsAt(_clubId, _tierId).length == 0, "!UNDELETEABLE - Cannot delete a Tier if there are still members in it. Please update Tier instead!"); Tier[] storage targetTiers = totalTiers[_clubId]; require(_tierId < targetTiers.length, "!TIER_ID - invalid _param.tierId"); for (uint256 i = _tierId; i < targetTiers.length - 1; i++) { targetTiers[i] = targetTiers[i+1]; totalSubscriptions[_clubId][i] = totalSubscriptions[_clubId][i+1]; } delete totalSubscriptions[_clubId][targetTiers.length]; }
5,629,047
[ 1, 48, 2413, 279, 3905, 373, 1807, 3410, 1430, 279, 399, 2453, 225, 389, 88, 2453, 548, 565, 2254, 5034, 300, 326, 4555, 434, 326, 17742, 358, 506, 4282, 19, 385, 16791, 1430, 279, 399, 2453, 309, 1915, 854, 4859, 4833, 316, 518, 336, 1018, 399, 2453, 526, 1954, 309, 1375, 67, 891, 18, 88, 2453, 548, 68, 3143, 358, 279, 923, 399, 2453, 4654, 1516, 358, 2913, 358, 5590, 326, 1018, 4282, 17742, 516, 18011, 752, 279, 4977, 1776, 603, 326, 1142, 761, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1430, 15671, 12, 11890, 5034, 389, 830, 373, 548, 16, 2254, 5034, 389, 88, 2453, 548, 13, 3903, 3849, 1338, 2009, 373, 5541, 24899, 830, 373, 548, 13, 1338, 2009, 373, 5541, 2996, 1435, 1338, 9895, 2009, 373, 24899, 830, 373, 548, 13, 288, 203, 3639, 2583, 12, 588, 15440, 861, 24899, 830, 373, 548, 16, 389, 88, 2453, 548, 2934, 2469, 422, 374, 16, 17528, 2124, 6460, 2782, 300, 14143, 1430, 279, 399, 2453, 309, 1915, 854, 4859, 4833, 316, 518, 18, 7801, 1089, 399, 2453, 3560, 4442, 1769, 203, 203, 3639, 399, 2453, 8526, 2502, 1018, 56, 20778, 273, 2078, 56, 20778, 63, 67, 830, 373, 548, 15533, 203, 203, 3639, 2583, 24899, 88, 2453, 548, 411, 1018, 56, 20778, 18, 2469, 16, 17528, 23240, 654, 67, 734, 300, 2057, 389, 891, 18, 88, 2453, 548, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 389, 88, 2453, 548, 31, 277, 411, 1018, 56, 20778, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 1018, 56, 20778, 63, 77, 65, 273, 1018, 56, 20778, 63, 77, 15, 21, 15533, 203, 5411, 2078, 15440, 63, 67, 830, 373, 548, 6362, 77, 65, 273, 2078, 15440, 63, 67, 830, 373, 548, 6362, 77, 15, 21, 15533, 203, 3639, 289, 203, 203, 3639, 1430, 2078, 15440, 63, 67, 830, 373, 548, 6362, 3299, 56, 20778, 18, 2469, 15533, 203, 203, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.8; import "../external/oraclizeAPI.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../interfaces/IOracle.sol"; contract PolyOracle is usingOraclize, IOracle, Ownable { using SafeMath for uint256; /*solium-disable-next-line max-len*/ string public oracleURL = "[URL] json(https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=2496&convert=USD&CMC_PRO_API_KEY=${[decrypt] BCA0Bqxmn3jkSENepaHxQv09Z/vGdEO9apO+B9RplHyV3qOL/dw5Indlei3hoXrGk9G14My8MFpHJycB7UoVnl+4mlzEsjTlS2UBAYVrl0fAepfiSyM30/GMZAoJmDagY+0YyNZvpkgXn86Q/59Bi48PWEet}).data.\"2496\".quote.USD.price"; string public oracleQueryType = "nested"; uint256 public sanityBounds = 20 * 10 ** 16; uint256 public gasLimit = 100000; uint256 public oraclizeTimeTolerance = 5 minutes; uint256 public staleTime = 6 hours; // POLYUSD poly units = 1 * 10^18 USD units (1 USD) uint256 private POLYUSD; uint256 public latestUpdate; uint256 public latestScheduledUpdate; mapping(bytes32 => uint256) public requestIds; mapping(bytes32 => bool) public ignoreRequestIds; mapping(address => bool) public admin; bool public freezeOracle; event PriceUpdated(uint256 _price, uint256 _oldPrice, bytes32 _queryId, uint256 _time); event NewOraclizeQuery(uint256 _time, bytes32 _queryId, string _query); event AdminSet(address _admin, bool _valid); event StalePriceUpdate(bytes32 _queryId, uint256 _time, string _result); modifier isAdminOrOwner() { require(admin[msg.sender] || msg.sender == owner(), "Address is not admin or owner"); _; } /** * @notice Constructor - accepts ETH to initialise a balance for subsequent Oraclize queries */ constructor() public payable { // Use 50 gwei for now oraclize_setCustomGasPrice(50 * 10 ** 9); } /** * @notice Oraclize callback (triggered by Oraclize) * @param _requestId requestId corresponding to Oraclize query * @param _result data returned by Oraclize URL query */ function __callback(bytes32 _requestId, string memory _result) public { require(msg.sender == oraclize_cbAddress(), "Only Oraclize can access this method"); require(!freezeOracle, "Oracle is frozen"); require(!ignoreRequestIds[_requestId], "Ignoring requestId"); if (requestIds[_requestId] < latestUpdate) { // Result is stale, probably because it was received out of order emit StalePriceUpdate(_requestId, requestIds[_requestId], _result); return; } require(requestIds[_requestId] >= latestUpdate, "Result is stale"); /*solium-disable-next-line security/no-block-members*/ require(requestIds[_requestId] <= now + oraclizeTimeTolerance, "Result is early"); uint256 newPOLYUSD = parseInt(_result, 18); uint256 bound = POLYUSD.mul(sanityBounds).div(10 ** 18); if (latestUpdate != 0) { require(newPOLYUSD <= POLYUSD.add(bound), "Result is too large"); require(newPOLYUSD >= POLYUSD.sub(bound), "Result is too small"); } latestUpdate = requestIds[_requestId]; emit PriceUpdated(newPOLYUSD, POLYUSD, _requestId, latestUpdate); POLYUSD = newPOLYUSD; } /** * @notice Allows owner to schedule future Oraclize calls * @param _times UNIX timestamps to schedule Oraclize calls as of. Empty list means trigger an immediate query. */ function schedulePriceUpdatesFixed(uint256[] memory _times) public payable isAdminOrOwner { bytes32 requestId; uint256 maximumScheduledUpdated; if (_times.length == 0) { require(oraclize_getPrice(oracleQueryType, gasLimit) <= address(this).balance, "Insufficient Funds"); requestId = oraclize_query(oracleQueryType, oracleURL, gasLimit); /*solium-disable-next-line security/no-block-members*/ requestIds[requestId] = now; /*solium-disable-next-line security/no-block-members*/ maximumScheduledUpdated = now; /*solium-disable-next-line security/no-block-members*/ emit NewOraclizeQuery(now, requestId, oracleURL); } else { require(oraclize_getPrice(oracleQueryType, gasLimit) * _times.length <= address(this).balance, "Insufficient Funds"); for (uint256 i = 0; i < _times.length; i++) { /*solium-disable-next-line security/no-block-members*/ require(_times[i] >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp"); requestId = oraclize_query(_times[i], oracleQueryType, oracleURL, gasLimit); requestIds[requestId] = _times[i]; if (maximumScheduledUpdated < requestIds[requestId]) { maximumScheduledUpdated = requestIds[requestId]; } emit NewOraclizeQuery(_times[i], requestId, oracleURL); } } if (latestScheduledUpdate < maximumScheduledUpdated) { latestScheduledUpdate = maximumScheduledUpdated; } } /** * @notice Allows owner to schedule future Oraclize calls on a rolling schedule * @param _startTime UNIX timestamp for the first scheduled Oraclize query * @param _interval how long (in seconds) between each subsequent Oraclize query * @param _iters the number of Oraclize queries to schedule. */ function schedulePriceUpdatesRolling(uint256 _startTime, uint256 _interval, uint256 _iters) public payable isAdminOrOwner { bytes32 requestId; require(_interval > 0, "Interval between scheduled time should be greater than zero"); require(_iters > 0, "No iterations specified"); /*solium-disable-next-line security/no-block-members*/ require(_startTime >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp"); require(oraclize_getPrice(oracleQueryType, gasLimit) * _iters <= address(this).balance, "Insufficient Funds"); for (uint256 i = 0; i < _iters; i++) { uint256 scheduledTime = _startTime + (i * _interval); requestId = oraclize_query(scheduledTime, oracleQueryType, oracleURL, gasLimit); requestIds[requestId] = scheduledTime; emit NewOraclizeQuery(scheduledTime, requestId, oracleURL); } if (latestScheduledUpdate < requestIds[requestId]) { latestScheduledUpdate = requestIds[requestId]; } } /** * @notice Allows owner to manually set POLYUSD price * @param _price POLYUSD price */ function setPOLYUSD(uint256 _price) public onlyOwner { /*solium-disable-next-line security/no-block-members*/ emit PriceUpdated(_price, POLYUSD, 0, now); POLYUSD = _price; /*solium-disable-next-line security/no-block-members*/ latestUpdate = now; } /** * @notice Allows owner to set oracle to ignore all Oraclize pricce updates * @param _frozen true to freeze updates, false to reenable updates */ function setFreezeOracle(bool _frozen) public onlyOwner { freezeOracle = _frozen; } /** * @notice Allows owner to set URL used in Oraclize queries * @param _oracleURL URL to use */ function setOracleURL(string memory _oracleURL) public onlyOwner { oracleURL = _oracleURL; } /** * @notice Allows owner to set type used in Oraclize queries * @param _oracleQueryType to use */ function setOracleQueryType(string memory _oracleQueryType) public onlyOwner { oracleQueryType = _oracleQueryType; } /** * @notice Allows owner to set new sanity bounds for price updates * @param _sanityBounds sanity bounds as a percentage * 10**16 */ function setSanityBounds(uint256 _sanityBounds) public onlyOwner { sanityBounds = _sanityBounds; } /** * @notice Allows owner to set new gas price for future Oraclize queries * @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled * @param _gasPrice gas price to use for Oraclize callbacks */ function setGasPrice(uint256 _gasPrice) public onlyOwner { oraclize_setCustomGasPrice(_gasPrice); } /** * @notice Returns price and corresponding update time * @return latest POLYUSD price * @return timestamp of latest price update */ function getPriceAndTime() public view returns(uint256, uint256) { return (POLYUSD, latestUpdate); } /** * @notice Allows owner to set new gas limit on Oraclize queries * @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled * @param _gasLimit gas limit to use for Oraclize callbacks */ function setGasLimit(uint256 _gasLimit) public isAdminOrOwner { gasLimit = _gasLimit; } /** * @notice Allows owner to set time after which price is considered stale * @param _staleTime elapsed time after which price is considered stale */ function setStaleTime(uint256 _staleTime) public onlyOwner { staleTime = _staleTime; } /** * @notice Allows owner to ignore specific requestId results from Oraclize * @param _requestIds Oraclize queryIds (as logged out when Oraclize query is scheduled) * @param _ignore whether or not they should be ignored */ function setIgnoreRequestIds(bytes32[] memory _requestIds, bool[] memory _ignore) public onlyOwner { require(_requestIds.length == _ignore.length, "Incorrect parameter lengths"); for (uint256 i = 0; i < _requestIds.length; i++) { ignoreRequestIds[_requestIds[i]] = _ignore[i]; } } /** * @notice Allows owner to set up admin addresses that can schedule updates * @param _admin Admin address * @param _valid Whether address should be added or removed from admin list */ function setAdmin(address _admin, bool _valid) public onlyOwner { admin[_admin] = _valid; /*solium-disable-next-line security/no-block-members*/ emit AdminSet(_admin, _valid); } /** * @notice Allows owner to set new time tolerance on Oraclize queries * @param _oraclizeTimeTolerance amount of time in seconds that an Oraclize query can be early */ function setOraclizeTimeTolerance(uint256 _oraclizeTimeTolerance) public onlyOwner { oraclizeTimeTolerance = _oraclizeTimeTolerance; } /** * @notice Returns address of oracle currency (0x0 for ETH) */ function getCurrencyAddress() external view returns(address) { return 0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC; } /** * @notice Returns symbol of oracle currency (0x0 for ETH) */ function getCurrencySymbol() external view returns(bytes32) { return bytes32("POLY"); } /** * @notice Returns denomination of price */ function getCurrencyDenominated() external view returns(bytes32) { return bytes32("USD"); } /** * @notice Returns price - should throw if not valid */ function getPrice() external returns(uint256) { /*solium-disable-next-line security/no-block-members*/ require(latestUpdate >= now - staleTime, "Invalid price"); return POLYUSD; } /** * @notice Returns balance to owner */ function drainContract() external onlyOwner { msg.sender.transfer(address(this).balance); } }
* @notice Allows owner to set new time tolerance on Oraclize queries @param _oraclizeTimeTolerance amount of time in seconds that an Oraclize query can be early/
function setOraclizeTimeTolerance(uint256 _oraclizeTimeTolerance) public onlyOwner { oraclizeTimeTolerance = _oraclizeTimeTolerance; }
5,396,811
[ 1, 19132, 3410, 358, 444, 394, 813, 10673, 603, 531, 354, 830, 554, 6218, 225, 389, 280, 10150, 554, 950, 22678, 3844, 434, 813, 316, 3974, 716, 392, 531, 354, 830, 554, 843, 848, 506, 11646, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 444, 51, 354, 830, 554, 950, 22678, 12, 11890, 5034, 389, 280, 10150, 554, 950, 22678, 13, 1071, 1338, 5541, 288, 203, 3639, 578, 10150, 554, 950, 22678, 273, 389, 280, 10150, 554, 950, 22678, 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 ]
./full_match/1/0x8787ca6A0aFffd8F634D09d7c2eE8D15b326e3f6/sources/src/lib/OptionalOnlyCaller.sol
* @dev Reverts if the verification mechanism is enabled and the given address is not the caller. @param user - Address to validate as the only allowed caller, if the verification is enabled./
modifier optionalOnlyCaller(address user) { _verifyCaller(user); _; }
2,980,100
[ 1, 426, 31537, 309, 326, 11805, 12860, 353, 3696, 471, 326, 864, 1758, 353, 486, 326, 4894, 18, 225, 729, 300, 5267, 358, 1954, 487, 326, 1338, 2935, 4894, 16, 309, 326, 11805, 353, 3696, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 9606, 3129, 3386, 11095, 12, 2867, 729, 13, 288, 203, 3639, 389, 8705, 11095, 12, 1355, 1769, 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, -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.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant 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) 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) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) 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) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract EAsset is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function EAsset() { balances[msg.sender] = 200000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to 20000000 * 1000000. (CHANGE THIS) totalSupply = 200000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "E-Asset"; // Set the name for display purposes (CHANGE THIS) decimals = 8; // Amount of decimals for display purposes (CHANGE THIS) symbol = "ASSET"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 20000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Set the name for display purposes (CHANGE THIS)
name = "E-Asset";
410,192
[ 1, 694, 326, 508, 364, 2562, 13694, 261, 14473, 20676, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 508, 273, 315, 41, 17, 6672, 14432, 4766, 565, 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 ]
./full_match/3/0x4fd708aa23cD006dCd77F8D7539f75Eb9147350C/sources/ride3.sol
The auction has already ended. There is a bid that is lower or matches your bid The auction has not ended yet. The function auctionEnd has already been called.
constructor (address payable _passengerWalletAddr, uint _durationMin, uint distanceKm, uint _startPostal, uint _endPostal) { passenger = _passengerWalletAddr; startPostal = _startPostal; endPostal = _endPostal; fareAmount = 5; lowestFareAmount = fareAmount; }
8,265,242
[ 1, 1986, 279, 4062, 711, 1818, 16926, 18, 6149, 353, 279, 9949, 716, 353, 2612, 578, 1885, 3433, 9949, 1021, 279, 4062, 711, 486, 16926, 4671, 18, 1021, 445, 279, 4062, 1638, 711, 1818, 2118, 2566, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3885, 261, 2867, 8843, 429, 389, 5466, 14348, 16936, 3178, 16, 2254, 389, 8760, 2930, 16, 2254, 3888, 47, 81, 16, 2254, 389, 1937, 3349, 287, 16, 2254, 389, 409, 3349, 287, 13, 288, 203, 540, 203, 3639, 1342, 14348, 273, 389, 5466, 14348, 16936, 3178, 31, 203, 3639, 787, 3349, 287, 273, 389, 1937, 3349, 287, 31, 203, 3639, 679, 3349, 287, 273, 389, 409, 3349, 287, 31, 203, 3639, 284, 834, 6275, 273, 1381, 31, 203, 3639, 11981, 42, 834, 6275, 273, 284, 834, 6275, 31, 203, 540, 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 ]
./partial_match/1/0x9b5D1e314a8c8AF17150fe4e327e8523ee15d25f/sources/contracts/mixins/NFTMarketReserveAuction.sol
@param endTime The timestamp at which the auction will end.
error NFTMarketReserveAuction_Cannot_Finalize_Auction_In_Progress(uint256 endTime);
4,363,726
[ 1, 409, 950, 1021, 2858, 622, 1492, 326, 279, 4062, 903, 679, 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, 1636, 423, 4464, 3882, 278, 607, 6527, 37, 4062, 67, 4515, 67, 7951, 554, 67, 37, 4062, 67, 382, 67, 5491, 12, 11890, 5034, 13859, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-07 */ /** *Submitted for verification at Etherscan.io on 2021-09-14 */ // File @openzeppelin/contracts/utils/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** * @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/token/ERC721/[email protected] /** * @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/[email protected] /** * @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/token/ERC721/extensions/[email protected] /** * @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/utils/[email protected] /** * @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 @openzeppelin/contracts/utils/[email protected] /* * @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/utils/[email protected] /** * @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/introspection/[email protected] /** * @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/[email protected] /** * @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(),".json")) : ""; } /** * @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 {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/access/[email protected] /** * @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); } } //Arq Skulls Physical Contract// contract BoardApeCollective is ERC721Enumerable, Ownable { address private _controlCenter; uint256 public constant max_apes = 2001; uint256 private _maxRedemption = 10; uint256 private _mintLimit = 10; uint256 private _price = 70000000000000000; //0.5 ETH uint256 private _memberPrice = 5000000000000000; uint256 private _publicSaleTime = 1642876500; uint256 private _whitelistSaleTime = 1642876200; ControlCenter private cc = ControlCenter(_controlCenter); string private _uriPrefix; string private _baseTokenURI; string private _provenanceHash; mapping(address => uint256) private _walletMinted; constructor(string memory baseURI, string memory provenanceHash) ERC721("Board Ape Collective", "BAC") { setBaseURI(baseURI); _provenanceHash = provenanceHash; _uriPrefix = "ipfs://"; //default to ipfs } function getControlCenter() public view returns(address){ return _controlCenter; } function setURIPrefix (string memory uriPrefix) public onlyOwner{ _uriPrefix = uriPrefix; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getProvenanceHash() public view returns(string memory) { return _provenanceHash; } function updateControlCenterAddress(address _cca) public onlyOwner { _controlCenter = _cca; } function _baseURI() internal view virtual override returns (string memory) { return string(abi.encodePacked(_uriPrefix,_baseTokenURI)); } function setPublicSaleTime(uint256 _time) public onlyOwner { _publicSaleTime = _time; } function setWhitelistSaleTime(uint256 _time) public onlyOwner { _whitelistSaleTime = _time; } function getSaleTime(address user) public view returns (uint256) { ControlCenter c = ControlCenter(_controlCenter); if(user !=address(0) ){ if(c.getBalance(user) > 0){ return _whitelistSaleTime; } else { return _publicSaleTime; } } else { return _publicSaleTime; } } function getBlockTime () public view returns(uint256) { return block.timestamp;} function getTimeUntilSale (address user) public view returns (uint256){ uint256 saleTime = getSaleTime(user); if(block.timestamp >= saleTime){ return 0; } else { return SafeMath.sub(saleTime,block.timestamp); } } function setPrice(uint256 _newWEIPrice) public onlyOwner { _price = _newWEIPrice; } function setMemberPrice(uint256 _newWEIPrice) public onlyOwner { _memberPrice = _newWEIPrice; } function getPrice() public view returns (uint256) { return _price; } function pairWithControlCenter(address _conCenter) public onlyOwner{ if(_controlCenter != _conCenter){ _controlCenter = _conCenter; } ControlCenter controlCenter = ControlCenter(_controlCenter); controlCenter.pairContract(address(this),_maxRedemption); } function getCallerPrice(uint256 _quantityMint) public view returns (uint256){ ControlCenter controlCenter = ControlCenter(_controlCenter); uint256 _eligibleBalance = controlCenter.getBalance(msg.sender); if(_eligibleBalance > 0){ return SafeMath.mul(_memberPrice,_quantityMint); } else { return SafeMath.mul(_price,_quantityMint); } } function mint(uint256 _count) public payable { uint256 totSupply = totalSupply(); require(block.timestamp >= getSaleTime(msg.sender), "Sale is not yet open."); require(totSupply < max_apes, "All Apes have been Claimed."); require(totSupply + _count <= max_apes,"There are not enough Apes available"); require(_walletMinted[msg.sender] + _count <= _maxRedemption, "Wallet would exceed mint limit"); require(msg.value == getCallerPrice(_count),"Price was not correct. Please send with the right amount of ETH."); for(uint i = 0; i < _count; i++) { uint mintIndex = totalSupply(); if (mintIndex < max_apes) { _safeMint(msg.sender, mintIndex); _walletMinted[msg.sender] ++; } } } 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)); } } abstract contract ControlCenter { //_tokenContractAddresses: Array of all potential ERC721 contracts that any token that interfaces with ControlCenter can access. address[] private _tokenContractAddresses; //_usingControlCenter keeps track of the contracts paired with this ControlCenter. address[] private _usingControlCenter; //owner: ControlCenter Owner address private owner; //_maxRedemptions: where address: Child Contract Address (external contract using the ControlCenter) mapped to the maximum number of redemptions allowed for that Child Contract (e.g. contract 0x123 only allows 3 redemptions per wallet); mapping(address=>uint256) private _maxRedemptions; //_activeTokenContracts: where address is one of the _contractAddress members mapped to a boolean denoting whether or not to ignore that contract in downstream functions. Setting this to false will effectively 'shut off' a specific contract from any considersations made by the ControlCenter mapping(address => bool) private _activeTokenContracts; //_contractEligibility: where address1 = similar to _activeTokenContracts but on a specific Child Contract level, setting [ChildContractAddress][TokenContractAddress] = false removes the [TokenContractAddress] from being considered as a redeemable token contract for the Child Contract. mapping(address=> mapping(address=>bool)) private _contractEligibility; mapping(address => mapping(address => mapping(uint256 => bool))) private tokenVer; //Mapping of [Child Contract] => [Corresponding ERC721 Token Contract] => [Corresponding ERC721 Token's Token ID] => [Redeemed (True/False)] whether a token has been redeemed for a specific Child Contract //_walletRedeemed: the number of tokens redeemed for a specific Child Contract. [Child Contract Address] => [Wallet Address] => [Number of Tokens Redeemed] mapping(address => mapping(address=>uint256)) private _walletRedeemed; constructor(){ owner = msg.sender; } /* *@dev Returns the balance of all active Token Contracts on the ControlCenter * @param _addy address Wallet address of a given user. */ function getBalance(address _addy) public view returns (uint256) { uint256 _balance =0; for (uint256 i=0;i<_tokenContractAddresses.length;i++){ if (_activeTokenContracts[_tokenContractAddresses[i]]){ _balance = SafeMath.add(_balance,ERC721(_tokenContractAddresses[i]).balanceOf(_addy)); } } return _balance; } /* *@dev Returns the maximum token redemptions allowed for a given Child Contract *Used to verify contract was onboarded to the ControlCenter correctly * @param _childContract address Address of a Child Contract implementing ControlCenter functions */ function checkContractStats(address _childContract) public view returns(uint256) { return (_maxRedemptions[_childContract]); } /*@dev This function checks the eligible balance of an address for a certain Child Contract. *While a caller may have any number of tokens, eligibility is determined by the maximum number of tokens a Child Contract supports as defined by the _maxRedemptions mapping and how many times a wallet *has redeemed tokens (_walletRedeemed) against the Child Contract (also determined by _maxRedemptions) *@param _childContract address Address of a Child Contract implementing ControlCenter functions *@param _addy address Wallet address of a given user (typically implemented as msg.sender from the Child Contract). */ function getEligibleBalance(address _childContract, address _addy) public view returns (uint256){ uint256 foundCount = 0; for (uint256 i = 0; i<_tokenContractAddresses.length;i++){ if(_contractEligibility[_childContract][_tokenContractAddresses[i]] && _activeTokenContracts[_tokenContractAddresses[i]]){ ERC721Enumerable con = ERC721Enumerable(_tokenContractAddresses[i]); uint256 conBalance = con.balanceOf(_addy); if ( conBalance > 0){ for (uint256 ii = 0; ii<conBalance; ii++){ ERC721Enumerable conE = ERC721Enumerable(_tokenContractAddresses[i]); uint256 tokenID = conE.tokenOfOwnerByIndex(_addy,ii); if(tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] == false){ foundCount++; } } } } } if (foundCount > 0){ if (foundCount >= _maxRedemptions[_childContract] && _maxRedemptions[_childContract] >= _walletRedeemed[_childContract][_addy]){ return SafeMath.sub(_maxRedemptions[_childContract], _walletRedeemed[_childContract][_addy]); } else if (foundCount<=_maxRedemptions[_childContract] && foundCount >= _walletRedeemed[_childContract][_addy]){ return SafeMath.sub(foundCount,_walletRedeemed[_childContract][_addy]); } else { return 0; } } else { return 0; } } /*@dev This function is called when onboarding a new Child Contract to this ControlCenter *@param _childContract address Address of a Child Contract implementing ControlCenter functions *@param _maxRed uint256 maximum number of tokens that can be redeemed against a certain Child Contract. */ function pairContract(address _childContract, uint256 _maxRed) public{ require(msg.sender == owner || msg.sender == _childContract, "Caller not authorized for this function"); _maxRedemptions[_childContract] = _maxRed; for(uint256 i =0; i<_tokenContractAddresses.length;i++){ _contractEligibility[_childContract][_tokenContractAddresses[i]] = true; } activateTokenContract(_childContract); } /*@dev This function can be used to manually override which Token Contracts are eligible to be redeemed for a certain Child Contract *@param _childContract address Address of a Child Contract implementing ControlCenter functions *@param _targetContract address Address of a target Token Contract whose state is being modified. *@param _newEligibility bool Whether or not the _targetContract can be redeemed against the given _childContract */ function setChildContractEligibility (address _childContract, address _targetContract, bool _newEligibility) public { require(msg.sender == owner || msg.sender == _childContract, "Caller not authorized for this function."); _contractEligibility[_childContract][_targetContract] = _newEligibility; } /*@dev This function handles the interal considerations for token redemptions. *This function in this version of ControlCenter is pretty indiscriminate in regards to which tokens it takes for redemption. *It's not so much concerned about what or where the tokens come from, so much as it is concerned that they are or are not available tokens to be redeemed. *If they are redeeemable per the Child Contract, then they're set to 'redeemed' and cannot be redeemed again for that particular Child Contract. *Additionally, redeeming a token from any given wallet will count against that wallet's total redemption number for a given Child Contract. *Once a token has been redeemed for a Child Contract it cannot be redeemed again, similarly a wallet cannot reduce the number of redemptions by sending a token elsewhere. *@param _childContract address Address of a Child Contract implementing ControlCenter functions *@param _redemptionNumber uint256 Number of tokens requested to be redeemed. *@param _addy address Wallet address of a given user (typically implemented as msg.sender from the Child Contract). */ function redeemEligibleTokens(address _childContract, uint256 _redemptionNumber, address _addy) public { //Must meet a number of requirements to continue to log a token as redeemed. require(msg.sender == owner || msg.sender == _childContract,"Caller not authorized for this function"); require(_redemptionNumber > 0, "Cannot redeem 0 tokens, you dork."); require(_walletRedeemed[_childContract][_addy] < _maxRedemptions[_childContract], "Caller has already redeemed maximum number of Tokens"); require(_redemptionNumber <= getEligibleBalance(_childContract, _addy),"This wallet cannot redeem this many tokens, please adjust_redemptionAmount"); require(getEligibleBalance(_childContract, _addy) > 0, "Caller has no Eligible Tokens for this Contract"); uint256 _foundCount = 0; uint256 _functionalLimit = getEligibleBalance(_childContract, _addy); //Functional limit is meant to cut down on potential wasted gas by taking the lesser of either what the user has opted to redeem or how many tokens the user is eligible to redeem if (_functionalLimit > _redemptionNumber) { _functionalLimit = _redemptionNumber; } if (_functionalLimit > 0){ //Seeks to save gas by breaking out of the loop if the _foundCount reaches the functionalLimit (meaning if it finds enough eligible tokens there's no point continuing to run the loop) for (uint256 i = 0; i<_tokenContractAddresses.length && _foundCount < _functionalLimit;i++){ if(_contractEligibility[_childContract][_tokenContractAddresses[i]] && _activeTokenContracts[_tokenContractAddresses[i]]){ ERC721Enumerable con = ERC721Enumerable(_tokenContractAddresses[i]); uint256 conBalance = con.balanceOf(_addy); //number of tokens owned by _addy on a given TokenContract[i] if ( conBalance > 0){ //similar gas saving effort here for (uint256 ii = 0; ii<conBalance && _foundCount < _functionalLimit; ii++){ ERC721Enumerable conE = ERC721Enumerable(_tokenContractAddresses[i]); uint256 tokenID = conE.tokenOfOwnerByIndex(_addy,ii); if(tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] == false){ tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] = true; _foundCount++; } } } } } } //Adds the number of foundTokens to the wallet's child contract mapping. This only occurs after all of the tokens have been set as redeemed. _walletRedeemed[_childContract][_addy] = SafeMath.add(_walletRedeemed[_childContract][_addy],_foundCount); } function checkTokenRedemptionStatus(address _childContract,address _tokenAddress, uint256 _tokenID) public view returns (bool){ return (tokenVer[_childContract][_tokenAddress][_tokenID]); } function activateTokenContract(address _contract) public { require(msg.sender == owner || msg.sender == _contract, "E:ActivateToken - Caller is not the owner"); require(_activeTokenContracts[_contract] == false, "Contract already active"); if(_isTokenContractOnControlCenter(_contract) == false){ _activeTokenContracts[_contract] = true; _tokenContractAddresses.push(_contract); } else { _activeTokenContracts[_contract] = true; } } function deactivateTokenContract(address _contract) public { require(msg.sender == owner, "Sender is not owner"); require(_activeTokenContracts[_contract] == true, "Contract isn't active."); _activeTokenContracts[_contract] = false; } function _isTokenContractOnControlCenter (address _contract) internal view returns(bool){ uint256 count = 0; for(uint256 i=0;i<_tokenContractAddresses.length;i++){ if(_tokenContractAddresses[i] == _contract){ count++; } } return count > 0; } function checkWalletRedeption(address _addy, address _childContract)public view returns(uint256){ return _walletRedeemed[_childContract][_addy]; } function viewControlCenterContracts() public view returns (address[] memory){ return _tokenContractAddresses; } }
* @dev Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
2,434,772
[ 1, 1356, 326, 2719, 434, 2795, 9088, 12321, 16, 15226, 310, 603, 9391, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 15, 68, 3726, 18, 29076, 30, 300, 1436, 608, 2780, 9391, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 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 ]
pragma solidity 0.5.11; // tests for most gas efficient way to flip a uint to the equiviliant negative int value // they were all tested in remix 0.5.11 with optimizer off and optimizer on at 200 cycles // they are the only functions in each contract because the evm adds 20 gas for each additional function or external variable ... 😡 // splitting hairs on gas differences here so probabaly wasn't worth the effort. the naive methods were actually slightly more efficient // ranked in order off optimized gas execuition cost, then unoptimized // can also test wider range of inputs //@dev naive subtraction contract A { //221 gas optimized 0.5.11, (1000000) input, as only function in contract //284 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return int256(0 - _num); } } //@dev naive subtraction, alt casting contract E { //221 gas optimized 0.5.11, (1000000) input, as only function in contract //284 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return 0 - int256(_num); } } //@dev assembly subtraction contract G { //221 gas optimized 0.5.11, (1000000) input, as only function in contract //284 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256 res) { assembly { res := sub(0, _num) } } } //@dev naive unary casting contract J { //221 gas optimized 0.5.11, (1000000) input, as only function in contract //284 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return -int256(_num); } } //@dev naive naive multiplication by -1 contract B { //221 gas optimized 0.5.11, (1000000) input, as only function in contract //287 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return int256(_num) * -1; } } //@dev naive unary casting contract D { //224 gas optimized 0.5.11, (1000000) input, as only function in contract //287 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return int256(~_num+1); } } //@dev bitwise `~` NOT, casting sequence #0 contract H { //224 gas unoptimized 0.5.11, (1000000) input, as only function in contract //287 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256 res) { assembly { res := add(not(_num), 1) } } } //@dev bitwise `~` NOT, alt casting sequence #1 contract C { //224 gas optimized 0.5.11, (1000000) input, as only function in contract //309 gas unoptimized 0.5.11, (1000000) input function flip(uint256 _num) public pure returns(int256) { return int256(~(_num)+1); } } //@dev bitwise `~` NOT, alt casting sequence #2 contract F { //227 gas optimized 0.5.11, (1000000) input, as only function in contract //287 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return ~int256(_num-1); } } //@dev `not` opcode in assembly contract I { //227 gas optimized 0.5.11, (1000000) input, as only function in contract //287 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256 res) { assembly { res := not(sub(_num, 1)) } } } //@dev bitwize XOR with bitmask contract K { //230 gas optimized 0.5.11, (1000000) input, as only function in contract //290 gas unoptimized 0.5.11, (1000000) input, as only function in contract function flip(uint256 _num) public pure returns(int256) { return int256(_num ^ 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) + 1; } } //other ideas: //appending first bit as signuature for pos/neg sig and writing custom methods to read that
@dev naive naive multiplication by -1221 gas optimized 0.5.11, (1000000) input, as only function in contract287 gas unoptimized 0.5.11, (1000000) input, as only function in contract
contract B { function flip(uint256 _num) public pure returns(int256) { return int256(_num) * -1; } }
14,075,875
[ 1, 6582, 688, 28224, 23066, 635, 300, 2138, 5340, 16189, 15411, 374, 18, 25, 18, 2499, 16, 261, 21, 9449, 13, 810, 16, 487, 1338, 445, 316, 6835, 6030, 27, 16189, 640, 16689, 1235, 374, 18, 25, 18, 2499, 16, 261, 21, 9449, 13, 810, 16, 487, 1338, 445, 316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 605, 288, 203, 377, 445, 9668, 12, 11890, 5034, 389, 2107, 13, 1071, 16618, 1135, 12, 474, 5034, 13, 288, 203, 3639, 327, 509, 5034, 24899, 2107, 13, 380, 300, 21, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xD3b9A1DCAbd16c482785Fd4265cB4580B84cdeD7/sources/tellor360/contracts/BaseToken.sol
* @dev This function approves a _spender an _amount of tokens to use @param _spender address receiving the allowance @param _amount amount the spender is being approved for @return bool true if spender approved successfully/
{ require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; }
9,800,627
[ 1, 2503, 445, 6617, 3324, 279, 389, 87, 1302, 264, 392, 389, 8949, 434, 2430, 358, 999, 225, 389, 87, 1302, 264, 1758, 15847, 326, 1699, 1359, 225, 389, 8949, 3844, 326, 17571, 264, 353, 3832, 20412, 364, 327, 1426, 638, 309, 17571, 264, 20412, 4985, 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, 288, 203, 3639, 2583, 24899, 87, 1302, 264, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 6617, 537, 358, 326, 3634, 1758, 8863, 203, 3639, 389, 5965, 6872, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 8949, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "./LibAddressSet.sol"; contract AddressSetDemo { using LibAddressSet for LibAddressSet.AddressSet; LibAddressSet.AddressSet private addressSet; event Log(uint256 size); function testAddress() public { //添加元素; addressSet.add(address(1)); // {1} // 查询set容器数量 uint256 size = addressSet.getSize(); require(size == 1); // 获取指定index的元素 address addr = addressSet.get(0); require(addr == (address(1)); // 返回set中所有的元素 addressSet.getAll(); // {0x1} // 判断元素是否存在 bool contains = addressSet.contains(address(1)); require(contains== true); // 删除元素 addressSet.remove(address(1)); } }
添加元素; {1} 查询set容器数量 获取指定index的元素 返回set中所有的元素 {0x1} 判断元素是否存在 删除元素
function testAddress() public { addressSet.add(address(1)); uint256 size = addressSet.getSize(); require(size == 1); address addr = addressSet.get(0); require(addr == (address(1)); addressSet.getAll(); bool contains = addressSet.contains(address(1)); require(contains== true); addressSet.remove(address(1)); }
2,544,004
[ 1, 167, 120, 124, 166, 237, 259, 166, 232, 230, 168, 117, 259, 176, 125, 254, 288, 21, 97, 225, 167, 258, 103, 169, 112, 100, 542, 166, 111, 122, 166, 252, 106, 167, 248, 113, 170, 234, 242, 225, 169, 241, 120, 166, 242, 249, 167, 239, 234, 166, 111, 253, 1615, 168, 253, 231, 166, 232, 230, 168, 117, 259, 225, 169, 128, 247, 166, 254, 257, 542, 165, 121, 260, 167, 236, 227, 167, 255, 236, 168, 253, 231, 166, 232, 230, 168, 117, 259, 288, 20, 92, 21, 97, 225, 166, 235, 102, 167, 249, 260, 166, 232, 230, 168, 117, 259, 167, 251, 112, 166, 243, 104, 166, 260, 251, 166, 255, 106, 225, 166, 235, 259, 170, 252, 102, 166, 232, 230, 168, 117, 259, 2, 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, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 1887, 1435, 1071, 288, 203, 3639, 1758, 694, 18, 1289, 12, 2867, 12, 21, 10019, 203, 3639, 2254, 5034, 963, 273, 1758, 694, 18, 588, 1225, 5621, 203, 3639, 2583, 12, 1467, 422, 404, 1769, 203, 3639, 1758, 3091, 273, 1758, 694, 18, 588, 12, 20, 1769, 203, 3639, 2583, 12, 4793, 422, 261, 2867, 12, 21, 10019, 203, 3639, 1758, 694, 18, 588, 1595, 5621, 203, 3639, 1426, 1914, 273, 1758, 694, 18, 12298, 12, 2867, 12, 21, 10019, 203, 3639, 2583, 12, 12298, 631, 638, 1769, 203, 3639, 1758, 694, 18, 4479, 12, 2867, 12, 21, 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 ]
./partial_match/4/0xb4F4B34d76656a27965e5eb5575259FBD4a205e7/sources/ANWNFToken.sol
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension/
contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) external view returns (string); }
8,597,648
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 1982, 2710, 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, 16351, 467, 654, 39, 27, 5340, 2277, 353, 467, 654, 39, 27, 5340, 288, 203, 225, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 1769, 203, 225, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 1769, 203, 225, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 1769, 203, 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 ]
./partial_match/56/0x3d6D415be40159f207540f95E398F29a7173dC20/sources/JetfuelVaultDittoBoost.sol
* @dev Implementation of a vault to deposit funds for yield optimizing. This is the contract that receives funds and that users interface with. The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract./
contract JetfuelVaultDittoBoost is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct StratCandidate { address implementation; uint256 proposedTime; } address public constant unirouter = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); address public constant wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant ditto = address(0x233d91A0713155003fc4DcE0AFa871b508B3B715); event NewStratCandidate(address implementation); event UpgradeStrat(address implementation); address _token, address _strategy, string memory _name, string memory _symbol, uint256 _approvalDelay ) public ERC20( string(abi.encodePacked(_name)), string(abi.encodePacked(_symbol)) ) StratCandidate public stratCandidate; address public strategy; IERC20 public token; uint256 public immutable approvalDelay; constructor( { token = IERC20(_token); strategy = _strategy; approvalDelay = _approvalDelay; IERC20(ditto).safeApprove(unirouter, uint256(-1)); IERC20(wbnb).safeApprove(unirouter, uint256(-1)); IERC20(token).safeApprove(unirouter, uint256(-1)); } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); } function available() public view returns (uint256) { return token.balanceOf(address(this)); } function getPricePerFullShare() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); } } else { function _path(address token0, address toke1) internal returns (address[] memory) { address[] memory path = new address[](2); path[0] = token0; path[1] = toke1; return path; } function addLiquidity(uint256 _amount) internal { uint256 halfAmount = _amount.div(2); IUniswapRouter(unirouter) .swapExactETHForTokensSupportingFeeOnTransferTokens{ value: halfAmount }(0, _path(wbnb, ditto), address(this), now.add(600)); uint256 dittoAmount = IERC20(ditto).balanceOf(address(this)); ditto, dittoAmount, 1, 1, address(this), now.add(600) ); } function addLiquidity(uint256 _amount) internal { uint256 halfAmount = _amount.div(2); IUniswapRouter(unirouter) .swapExactETHForTokensSupportingFeeOnTransferTokens{ value: halfAmount }(0, _path(wbnb, ditto), address(this), now.add(600)); uint256 dittoAmount = IERC20(ditto).balanceOf(address(this)); ditto, dittoAmount, 1, 1, address(this), now.add(600) ); } IUniswapRouter(unirouter).addLiquidityETH{value: halfAmount}( function depositBNB() public payable { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); uint256 _amount = 0; addLiquidity(msg.value); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); } function depositBNB() public payable { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); uint256 _amount = 0; addLiquidity(msg.value); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); } } else { msg.sender.transfer(address(this).balance); function earn() public { uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } function withdrawAllBNB() external { withdrawBNB(balanceOf(msg.sender)); } function withdraw(uint256 _shares) public { uint256 _withdraw = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 _before = token.balanceOf(address(this)); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(_before); token.safeTransfer(msg.sender, _diff); } function withdrawBNB(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } IUniswapRouter(unirouter) .removeLiquidityETHSupportingFeeOnTransferTokens( address(ditto), r, 1, 1, address(this), now.add(600) ); uint256 dittoAmount = IERC20(ditto).balanceOf(address(this)); IUniswapRouter(unirouter) .swapExactTokensForETHSupportingFeeOnTransferTokens( dittoAmount, 0, _path(ditto, wbnb), address(this), now.add(600) ); msg.sender.transfer(address(this).balance); } function withdrawBNB(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } IUniswapRouter(unirouter) .removeLiquidityETHSupportingFeeOnTransferTokens( address(ditto), r, 1, 1, address(this), now.add(600) ); uint256 dittoAmount = IERC20(ditto).balanceOf(address(this)); IUniswapRouter(unirouter) .swapExactTokensForETHSupportingFeeOnTransferTokens( dittoAmount, 0, _path(ditto, wbnb), address(this), now.add(600) ); msg.sender.transfer(address(this).balance); } function withdrawBNB(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } IUniswapRouter(unirouter) .removeLiquidityETHSupportingFeeOnTransferTokens( address(ditto), r, 1, 1, address(this), now.add(600) ); uint256 dittoAmount = IERC20(ditto).balanceOf(address(this)); IUniswapRouter(unirouter) .swapExactTokensForETHSupportingFeeOnTransferTokens( dittoAmount, 0, _path(ditto, wbnb), address(this), now.add(600) ); msg.sender.transfer(address(this).balance); } function proposeStrat(address _implementation) public onlyOwner { stratCandidate = StratCandidate({ implementation: _implementation, proposedTime: block.timestamp }); emit NewStratCandidate(_implementation); } function proposeStrat(address _implementation) public onlyOwner { stratCandidate = StratCandidate({ implementation: _implementation, proposedTime: block.timestamp }); emit NewStratCandidate(_implementation); } function upgradeStrat() public onlyOwner { require( stratCandidate.implementation != address(0), "There is no candidate" ); require( stratCandidate.proposedTime.add(approvalDelay) < block.timestamp, "Delay has not passed" ); emit UpgradeStrat(stratCandidate.implementation); strategy = stratCandidate.implementation; stratCandidate.implementation = address(0); stratCandidate.proposedTime = 5000000000; earn(); } receive() external payable {} }
11,118,454
[ 1, 13621, 434, 279, 9229, 358, 443, 1724, 284, 19156, 364, 2824, 5213, 6894, 18, 1220, 353, 326, 6835, 716, 17024, 284, 19156, 471, 716, 3677, 1560, 598, 18, 1021, 2824, 5213, 6894, 6252, 6174, 353, 8249, 316, 279, 9004, 296, 4525, 18, 18281, 11, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 804, 27227, 20317, 12003, 40, 305, 869, 26653, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 1958, 3978, 270, 11910, 288, 203, 3639, 1758, 4471, 31, 203, 3639, 2254, 5034, 20084, 950, 31, 203, 565, 289, 203, 203, 203, 565, 1758, 1071, 5381, 7738, 10717, 273, 203, 3639, 1758, 12, 20, 92, 6260, 74, 42, 22, 38, 20, 2290, 8148, 7950, 28, 37, 8642, 3361, 70, 2486, 13459, 24, 74, 29, 73, 3437, 69, 40, 72, 4848, 28, 39, 27, 42, 1769, 203, 203, 565, 1758, 1071, 5381, 17298, 6423, 273, 203, 3639, 1758, 12, 20, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 1769, 203, 203, 565, 1758, 1071, 5381, 302, 305, 869, 273, 203, 3639, 1758, 12, 20, 92, 31026, 72, 12416, 37, 8642, 3437, 23643, 25425, 7142, 24, 40, 71, 41, 20, 6799, 69, 11035, 21, 70, 3361, 28, 38, 23, 38, 27, 3600, 1769, 203, 203, 565, 871, 1166, 1585, 270, 11910, 12, 2867, 4471, 1769, 203, 565, 871, 17699, 1585, 270, 12, 2867, 4471, 1769, 203, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 14914, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2 ]
./full_match/5/0x74807E0EB3CEf9a9366419372E873286572112f1/sources/OpenNFTs/contracts/OpenNFTs/OpenMarketable.sol
Transfer back unspent funds to buyer
unspent = _transferValue(buyer, unspent);
1,920,339
[ 1, 5912, 1473, 640, 20693, 284, 19156, 358, 27037, 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, 3639, 640, 20693, 273, 389, 13866, 620, 12, 70, 16213, 16, 640, 20693, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ uint256 private constant AIRLINE_FUND_AMOUNT = 10 ether; uint256 private constant INSURANCE_FUND_AMOUNT = 1 ether; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint constant M = 4; // min number of multi-party voters uint private numVoted = 0; uint airlinesCount = 0; address[] multiCalls = new address[](0); // all of the addresses that have called the multi-party consensus function // address[] multiAirlineCalls = new address[](0); // all of the airlines that have called the multi-party consensus, vote function struct Passenger { bool purchasedInsurance; address wallet; uint256 insurancePaid; uint256 insurancePayout; bool insurancePayoutComplete; } mapping(address => Passenger) public passengers; mapping(bytes32 => address []) public passengersWhoBoughtInsurance; // track those passengers who purchasesed insurance for the flight mapping(address => uint256) public insurancePayout; // track insurance payout amount by passenger mapping(bytes32 => uint256[]) public amountInsuredForFlight; mapping(address => bool) private hasVoted; // track airline consesnsus voting address[] public registeredAirlines; // track registered airline address struct UserProfile { bool isRegistered; bool isAdmin; } mapping(address => UserProfile) userProfiles; struct Airline { bool isRegistered; uint numVotes; bool hasFunds; bool hasVoted; string name; address wallet; uint256 funds; } // Airline[] private airlines; mapping(address => Airline) airlines; mapping(address => uint256) private authorizedContracts; // list of authorized contracts that can call this data contract /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; authorizedContracts[msg.sender] = 1; // register the first airline airlines[msg.sender] = Airline({isRegistered: true, numVotes: 0, hasFunds: false, hasVoted: false, name: "first airline", wallet: msg.sender, funds: 0 }); numVoted = 0; airlinesCount++; registeredAirlines.push(msg.sender); // track registered airlines so that i can iterate over array of airlines. } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // need to ensure that the calling contract is authorized modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Check if a user is registered * * @return A bool that indicates if the user is registered */ function isUserRegistered ( address account ) external view returns(bool) { require(account != address(0), "'account' must be a valid address."); return userProfiles[account].isRegistered; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function registerUser ( address account, bool isAdmin ) external requireIsOperational requireContractOwner { require(!userProfiles[account].isRegistered, "User is already registered."); userProfiles[account] = UserProfile({ isRegistered: true, isAdmin: isAdmin }); } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } // authorize the calling contract(s) to restrict data contract callers function authorizeContract ( address contractAddress ) external requireContractOwner { authorizedContracts[contractAddress] = 1; } // function to check to see if the calling contract is authorized to call this data contract function isCallerAuthorized(address callingContract) external view returns(bool) { return (authorizedContracts[callingContract] == 1); } // deauthorize the calling contract function deauthorizeContract ( address contractAddress ) external requireContractOwner { delete authorizedContracts[contractAddress]; } // verify that the airline is valid by ensuring it is funded. function isAirline(address airline) external view returns(bool) { return (airlines[airline].hasFunds == true); } // retrieve airline funds function airlineFunds(address airline) external view returns (uint256) { return (airlines[airline].funds); } function isAirlineRegistered ( address account ) external view returns(bool) { require(account != address(0),"'airline' must be a valid address"); return airlines[account].isRegistered; } function getPassenger(address passenger) requireIsOperational external view returns (bool , uint256, uint256, bool) { return ( passengers[passenger].purchasedInsurance, passengers[passenger].insurancePaid, passengers[passenger].insurancePayout, passengers[passenger].insurancePayoutComplete ); } function getPassengerInsurancePayout(address passenger) requireIsOperational external view returns (uint256) { return (passengers[passenger].insurancePayout ); } function getAirline(address airline) requireIsOperational public view returns (bool registered, bool hasfunds, string name, uint256 funds, uint numVotes,uint256 numairlines) { return ( airlines[airline].isRegistered, airlines[airline].hasFunds, airlines[airline].name, airlines[airline].funds, airlines[airline].numVotes, airlinesCount ); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getInsurancePayout(address passenger) external view returns (uint256) { //return insurancePayout[passenger]; return 1500000000000000000; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline, string airlinename ) external requireIsOperational requireIsCallerAuthorized { //require(!airlines[airline].isRegistered,"Airline is already registered."); if (airlinesCount < M) { airlines[airline] = Airline({isRegistered: true,hasFunds: false, hasVoted:false, numVotes: 1,funds: 0,name: airlinename, wallet: airline}); registeredAirlines.push(airline); airlinesCount++; } else { if (!hasVoted[msg.sender]) { numVoted++; airlines[airline].numVotes++; // need at least 50% consensus if (airlines[airline].numVotes >= airlinesCount.div(2)) { // reset the voting for (uint i = 0; i < registeredAirlines.length; i++) { hasVoted[registeredAirlines[i]] = false; } airlines[airline] = Airline({isRegistered: true,hasFunds: false, hasVoted:false, numVotes: numVoted,funds: 0,name: airlinename, wallet: airline}); numVoted = 0; registeredAirlines.push(airline); airlinesCount++; } } } } /** * @dev Buy insurance for a flight * */ function buy ( address airline, string flightCode, uint256 timestamp ) requireIsOperational external payable { require(msg.value >= INSURANCE_FUND_AMOUNT, "Insufficient funds to purchase flight insurance"); require(msg.sender == tx.origin, "Unauthorized Contract"); bytes32 flightkey = getFlightKey(airline,flightCode,timestamp); // track passengers who bought insurance passengers[msg.sender] = Passenger({purchasedInsurance: true, insurancePaid: msg.value,insurancePayout: msg.value, wallet: msg.sender, insurancePayoutComplete: false}); passengersWhoBoughtInsurance[flightkey].push(msg.sender); // track amount of insurance purchased for the flight amountInsuredForFlight[flightkey].push(msg.value); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flightKey ) external requireIsOperational { address passengerWallet; uint256 insuranceToPayout; uint256 passengerPaid; for (uint i = 0; i < passengersWhoBoughtInsurance[flightKey].length; i++) { passengerWallet = passengersWhoBoughtInsurance[flightKey][i]; passengerPaid = passengers[passengerWallet].insurancePaid; insuranceToPayout = passengerPaid.mul(15).div(10); insurancePayout[passengerWallet] = insuranceToPayout; passengers[passengerWallet] = Passenger ({ purchasedInsurance: true, wallet:passengerWallet, insurancePaid:passengerPaid, insurancePayout:insuranceToPayout, insurancePayoutComplete:true}); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address account ) requireIsOperational external payable { require(msg.value <= passengers[account].insurancePayout,"cannot withdraw more than what is in the insurance payout"); uint256 withdrawalAmount = passengers[account].insurancePayout; passengers[account].insurancePayout = 0; insurancePayout[account] = 0; account.transfer(withdrawalAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address airline ) public payable { airlines[airline].funds += msg.value; // when airline has the required funds to Vote, set hasFunds to true airlines[airline].hasFunds = true; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
* @dev Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining/ when airline has the required funds to Vote, set hasFunds to true
function fund ( address airline ) public payable { airlines[airline].funds += msg.value; airlines[airline].hasFunds = true; }
14,034,092
[ 1, 4435, 22058, 364, 326, 2763, 295, 1359, 18, 1351, 2656, 1915, 854, 4885, 4906, 15278, 1183, 10730, 1377, 8156, 316, 2763, 295, 1359, 293, 2012, 87, 16, 326, 6835, 1410, 506, 365, 17, 87, 641, 3280, 19, 1347, 23350, 1369, 711, 326, 1931, 284, 19156, 358, 27540, 16, 444, 711, 42, 19156, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 284, 1074, 203, 18701, 261, 203, 17311, 1758, 23350, 1369, 203, 18701, 262, 203, 18701, 1071, 203, 18701, 8843, 429, 203, 565, 288, 203, 1377, 23350, 3548, 63, 1826, 1369, 8009, 74, 19156, 1011, 1234, 18, 1132, 31, 203, 1377, 23350, 3548, 63, 1826, 1369, 8009, 5332, 42, 19156, 273, 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, -100, -100, -100, -100, -100, -100, -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 pragma solidity ^0.8.0; import "./ShackledStructs.sol"; import "./ShackledMath.sol"; import "./Trigonometry.sol"; /* dir codes: 0: right-left 1: left-right 2: up-down 3: down-up sel codes: 0: random 1: biggest-first 2: smallest-first */ library ShackledGenesis { uint256 constant MAX_N_ATTEMPTS = 150; // max number of attempts to find a valid triangle int256 constant ROT_XY_MAX = 12; // max amount of rotation in xy plane int256 constant MAX_CANVAS_SIZE = 32000; // max size of canvas /// a struct to hold vars in makeFacesVertsCols() to prevent StackTooDeep struct FacesVertsCols { uint256[3][] faces; int256[3][] verts; int256[3][] cols; uint256 nextColIdx; uint256 nextVertIdx; uint256 nextFaceIdx; } /** @dev generate all parameters required for the shackled renderer from a seed hash @param tokenHash a hash of the tokenId to be used in 'random' number generation */ function generateGenesisPiece(bytes32 tokenHash) external view returns ( ShackledStructs.RenderParams memory renderParams, ShackledStructs.Metadata memory metadata ) { /// initial model paramaters renderParams.objScale = 1; renderParams.objPosition = [int256(0), 0, -2500]; /// generate the geometry and colors ( FacesVertsCols memory vars, ColorUtils.ColScheme memory colScheme, GeomUtils.GeomSpec memory geomSpec, GeomUtils.GeomVars memory geomVars ) = generateGeometryAndColors(tokenHash, renderParams.objPosition); renderParams.faces = vars.faces; renderParams.verts = vars.verts; renderParams.cols = vars.cols; /// use a perspective camera renderParams.perspCamera = true; if (geomSpec.id == 3) { renderParams.wireframe = false; renderParams.backfaceCulling = true; } else { /// determine wireframe trait (5% chance) if (GeomUtils.randN(tokenHash, "wireframe", 1, 100) > 95) { renderParams.wireframe = true; renderParams.backfaceCulling = false; } else { renderParams.wireframe = false; renderParams.backfaceCulling = true; } } if ( colScheme.id == 2 || colScheme.id == 3 || colScheme.id == 7 || colScheme.id == 8 ) { renderParams.invert = false; } else { /// inversion (40% chance) renderParams.invert = GeomUtils.randN(tokenHash, "invert", 1, 10) > 6; } /// background colors renderParams.backgroundColor = [ colScheme.bgColTop, colScheme.bgColBottom ]; /// lighting parameters renderParams.lightingParams = ShackledStructs.LightingParams({ applyLighting: true, lightAmbiPower: 0, lightDiffPower: 2000, lightSpecPower: 3000, inverseShininess: 10, lightColSpec: colScheme.lightCol, lightColDiff: colScheme.lightCol, lightColAmbi: colScheme.lightCol, lightPos: [int256(-50), 0, 0] }); /// create the metadata metadata.colorScheme = colScheme.name; metadata.geomSpec = geomSpec.name; metadata.nPrisms = geomVars.nPrisms; if (geomSpec.isSymmetricX) { if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Diagonal"; } else { metadata.pseudoSymmetry = "Horizontal"; } } else if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Vertical"; } else { metadata.pseudoSymmetry = "Scattered"; } if (renderParams.wireframe) { metadata.wireframe = "Enabled"; } else { metadata.wireframe = "Disabled"; } if (renderParams.invert) { metadata.inversion = "Enabled"; } else { metadata.inversion = "Disabled"; } } /** @dev run a generative algorithm to create 3d geometries (prisms) and colors to render with Shackled also returns the faces and verts, which can be used to build a .obj file for in-browser rendering */ function generateGeometryAndColors( bytes32 tokenHash, int256[3] memory objPosition ) internal view returns ( FacesVertsCols memory vars, ColorUtils.ColScheme memory colScheme, GeomUtils.GeomSpec memory geomSpec, GeomUtils.GeomVars memory geomVars ) { /// get this geom's spec geomSpec = GeomUtils.generateSpec(tokenHash); /// create the triangles ( int256[3][3][] memory tris, int256[] memory zFronts, int256[] memory zBacks ) = create2dTris(tokenHash, geomSpec); /// prismify geomVars = prismify(tokenHash, tris, zFronts, zBacks); /// generate colored faces /// get a color scheme colScheme = ColorUtils.getScheme(tokenHash, tris); /// get faces, verts and colors vars = makeFacesVertsCols( tokenHash, tris, geomVars, colScheme, objPosition ); } /** @dev 'randomly' create an array of 2d triangles that will define each eventual 3d prism */ function create2dTris(bytes32 tokenHash, GeomUtils.GeomSpec memory geomSpec) internal view returns ( int256[3][3][] memory, /// tris int256[] memory, /// zFronts int256[] memory /// zBacks ) { /// initiate vars that will be used to store the triangle info GeomUtils.TriVars memory triVars; triVars.tris = new int256[3][3][]((geomSpec.maxPrisms + 5) * 2); triVars.zFronts = new int256[]((geomSpec.maxPrisms + 5) * 2); triVars.zBacks = new int256[]((geomSpec.maxPrisms + 5) * 2); /// 'randomly' initiate the starting radius int256 initialSize; if (geomSpec.forceInitialSize == 0) { initialSize = GeomUtils.randN( tokenHash, "size", geomSpec.minTriRad, geomSpec.maxTriRad ); } else { initialSize = geomSpec.forceInitialSize; } /// 50% chance of 30deg rotation, 50% chance of 210deg rotation int256 initialRot = GeomUtils.randN(tokenHash, "rot", 0, 1) == 0 ? int256(30) : int256(210); /// create the first triangle int256[3][3] memory currentTri = GeomUtils.makeTri( [int256(0), 0, 0], initialSize, initialRot ); /// save it triVars.tris[0] = currentTri; /// calculate the first triangle's zs triVars.zBacks[0] = GeomUtils.calculateZ( currentTri, tokenHash, triVars.nextTriIdx, geomSpec, false ); triVars.zFronts[0] = GeomUtils.calculateZ( currentTri, tokenHash, triVars.nextTriIdx, geomSpec, true ); /// get the position to add the next triangle if (geomSpec.isSymmetricY) { /// override the first tri, since it is not symmetrical /// but temporarily save it as its needed as a reference tri triVars.nextTriIdx = 0; } else { triVars.nextTriIdx = 1; } /// make new triangles for (uint256 i = 0; i < MAX_N_ATTEMPTS; i++) { /// get a reference to a previous triangle uint256 refIdx = uint256( GeomUtils.randN( tokenHash, string(abi.encodePacked("refIdx", i)), 0, int256(triVars.nextTriIdx) - 1 ) ); /// ensure that the 'random' number generated is different in each while loop /// by incorporating the nAttempts and nextTriIdx into the seed modifier if ( GeomUtils.randN( tokenHash, string(abi.encodePacked("adj", i, triVars.nextTriIdx)), 0, 100 ) <= geomSpec.probVertOpp ) { /// attempt to recursively add vertically opposite triangles triVars = GeomUtils.makeVerticallyOppositeTriangles( tokenHash, i, // attemptNum (to create unique random seeds) refIdx, triVars, geomSpec, -1, -1, 0 // depth (to create unique random seeds within recursion) ); } else { /// attempt to recursively add adjacent triangles triVars = GeomUtils.makeAdjacentTriangles( tokenHash, i, // attemptNum (to create unique random seeds) refIdx, triVars, geomSpec, -1, -1, 0 // depth (to create unique random seeds within recursion) ); } /// can't have this many triangles if (triVars.nextTriIdx >= geomSpec.maxPrisms) { break; } } /// clip all the arrays to the actual number of triangles triVars.tris = GeomUtils.clipTrisToLength( triVars.tris, triVars.nextTriIdx ); triVars.zBacks = GeomUtils.clipZsToLength( triVars.zBacks, triVars.nextTriIdx ); triVars.zFronts = GeomUtils.clipZsToLength( triVars.zFronts, triVars.nextTriIdx ); return (triVars.tris, triVars.zBacks, triVars.zFronts); } /** @dev prismify the initial 2d triangles output */ function prismify( bytes32 tokenHash, int256[3][3][] memory tris, int256[] memory zFronts, int256[] memory zBacks ) internal view returns (GeomUtils.GeomVars memory) { /// initialise a struct to hold the vars we need GeomUtils.GeomVars memory geomVars; /// record the num of prisms geomVars.nPrisms = uint256(tris.length); /// figure out what point to put in the middle geomVars.extents = GeomUtils.getExtents(tris); // mins[3], maxs[3] /// scale the tris to fit in the canvas geomVars.width = geomVars.extents[1][0] - geomVars.extents[0][0]; geomVars.height = geomVars.extents[1][1] - geomVars.extents[0][1]; geomVars.extent = ShackledMath.max(geomVars.width, geomVars.height); geomVars.scaleNum = 2000; /// multiple all tris by the scale, then divide by the extent for (uint256 i = 0; i < tris.length; i++) { tris[i] = [ ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][0], geomVars.scaleNum ), geomVars.extent ), ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][1], geomVars.scaleNum ), geomVars.extent ), ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][2], geomVars.scaleNum ), geomVars.extent ) ]; } /// we may like to do some rotation, this means we get the shapes in the middle /// arrow up, down, left, right // 50% chance of x, y rotation being positive or negative geomVars.rotX = (GeomUtils.randN(tokenHash, "rotX", 0, 1) == 0) ? ROT_XY_MAX : -ROT_XY_MAX; geomVars.rotY = (GeomUtils.randN(tokenHash, "rotY", 0, 1) == 0) ? ROT_XY_MAX : -ROT_XY_MAX; // 50% chance to z rotation being 0 or 30 geomVars.rotZ = (GeomUtils.randN(tokenHash, "rotZ", 0, 1) == 0) ? int256(0) : int256(30); /// rotate all tris around facing (z) axis for (uint256 i = 0; i < tris.length; i++) { tris[i] = GeomUtils.triRotHelp(2, tris[i], geomVars.rotZ); } geomVars.trisBack = GeomUtils.copyTris(tris); geomVars.trisFront = GeomUtils.copyTris(tris); /// front triangles need to come forward, back triangles need to go back for (uint256 i = 0; i < tris.length; i++) { for (uint256 j = 0; j < 3; j++) { for (uint256 k = 0; k < 3; k++) { if (k == 2) { /// get the z values (make sure the scale is applied) geomVars.trisFront[i][j][k] = zFronts[i]; geomVars.trisBack[i][j][k] = zBacks[i]; } else { /// copy the x and y values geomVars.trisFront[i][j][k] = tris[i][j][k]; geomVars.trisBack[i][j][k] = tris[i][j][k]; } } } } /// rotate - order is import here (must come after prism splitting, and is dependant on z rotation) if (geomVars.rotZ == 0) { /// x then y (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 0, geomVars.trisBack, geomVars.trisFront, geomVars.rotX ); (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 1, geomVars.trisBack, geomVars.trisFront, geomVars.rotY ); } else { /// y then x (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 1, geomVars.trisBack, geomVars.trisFront, geomVars.rotY ); (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 0, geomVars.trisBack, geomVars.trisFront, geomVars.rotX ); } return geomVars; } /** @dev create verts and faces out of the geom and get their colors */ function makeFacesVertsCols( bytes32 tokenHash, int256[3][3][] memory tris, GeomUtils.GeomVars memory geomVars, ColorUtils.ColScheme memory scheme, int256[3] memory objPosition ) internal view returns (FacesVertsCols memory vars) { /// the tris defined thus far are those at the front of each prism /// we need to calculate how many tris will then be in the final prisms (3 sides have 2 tris each, plus the front tri, = 7) uint256 numTrisPrisms = tris.length * 7; /// 7 tris per 3D prism (not inc. back) vars.faces = new uint256[3][](numTrisPrisms); /// array that holds indexes of verts needed to make each final triangle vars.verts = new int256[3][](tris.length * 6); /// the vertices for all final triangles vars.cols = new int256[3][](tris.length * 6); /// 1 col per final tri vars.nextColIdx = 0; vars.nextVertIdx = 0; vars.nextFaceIdx = 0; /// get some number of highlight triangles geomVars.hltPrismIdx = ColorUtils.getHighlightPrismIdxs( tris, tokenHash, scheme.hltNum, scheme.hltVarCode, scheme.hltSelCode ); int256[3][2] memory frontExtents = GeomUtils.getExtents( geomVars.trisFront ); // mins[3], maxs[3] int256[3][2] memory backExtents = GeomUtils.getExtents( geomVars.trisBack ); // mins[3], maxs[3] int256[3][2] memory meanExtents = [ [ (frontExtents[0][0] + backExtents[0][0]) / 2, (frontExtents[0][1] + backExtents[0][1]) / 2, (frontExtents[0][2] + backExtents[0][2]) / 2 ], [ (frontExtents[1][0] + backExtents[1][0]) / 2, (frontExtents[1][1] + backExtents[1][1]) / 2, (frontExtents[1][2] + backExtents[1][2]) / 2 ] ]; /// apply translations such that we're at the center geomVars.center = ShackledMath.vector3DivScalar( ShackledMath.vector3Add(meanExtents[0], meanExtents[1]), 2 ); geomVars.center[2] = 0; for (uint256 i = 0; i < tris.length; i++) { int256[3][6] memory prismCols; ColorUtils.SubScheme memory subScheme = ColorUtils.inArray( geomVars.hltPrismIdx, i ) ? scheme.hlt : scheme.pri; /// get the colors for the prism prismCols = ColorUtils.getColForPrism( tokenHash, geomVars.trisFront[i], subScheme, meanExtents ); /// save the colors (6 per prism) for (uint256 j = 0; j < 6; j++) { vars.cols[vars.nextColIdx] = prismCols[j]; vars.nextColIdx++; } /// add 3 points (back) for (uint256 j = 0; j < 3; j++) { vars.verts[vars.nextVertIdx] = [ geomVars.trisBack[i][j][0], geomVars.trisBack[i][j][1], -geomVars.trisBack[i][j][2] /// flip the Z ]; vars.nextVertIdx += 1; } /// add 3 points (front) for (uint256 j = 0; j < 3; j++) { vars.verts[vars.nextVertIdx] = [ geomVars.trisFront[i][j][0], geomVars.trisFront[i][j][1], -geomVars.trisFront[i][j][2] /// flip the Z ]; vars.nextVertIdx += 1; } /// create the faces uint256 ii = i * 6; /// the orders are all important here (back is not visible) /// front vars.faces[vars.nextFaceIdx] = [ii + 3, ii + 4, ii + 5]; /// side 1 flat vars.faces[vars.nextFaceIdx + 1] = [ii + 4, ii + 3, ii + 0]; vars.faces[vars.nextFaceIdx + 2] = [ii + 0, ii + 1, ii + 4]; /// side 2 rhs vars.faces[vars.nextFaceIdx + 3] = [ii + 5, ii + 4, ii + 1]; vars.faces[vars.nextFaceIdx + 4] = [ii + 1, ii + 2, ii + 5]; /// side 3 lhs vars.faces[vars.nextFaceIdx + 5] = [ii + 2, ii + 0, ii + 3]; vars.faces[vars.nextFaceIdx + 6] = [ii + 3, ii + 5, ii + 2]; vars.nextFaceIdx += 7; } for (uint256 i = 0; i < vars.verts.length; i++) { vars.verts[i] = ShackledMath.vector3Sub( vars.verts[i], geomVars.center ); } } } /** Hold some functions useful for coloring in the prisms */ library ColorUtils { /// a struct to hold vars within the main color scheme /// which can be used for both highlight (hlt) an primar (pri) colors struct SubScheme { int256[3] colA; // either the entire solid color, or one side of the gradient int256[3] colB; // either the same as A (solid), or different (gradient) bool isInnerGradient; // whether the gradient spans the triangle (true) or canvas (false) int256 dirCode; // which direction should the gradient be interpolated int256[3] jiggle; // how much to randomly jiffle the color space bool isJiggleInner; // does each inner vertiex get a jiggle, or is it triangle wide int256[3] backShift; // how much to take off the back face colors } /// a struct for each piece's color scheme struct ColScheme { string name; uint256 id; /// the primary color SubScheme pri; /// the highlight color SubScheme hlt; /// remaining parameters (not common to hlt and pri) uint256 hltNum; int256 hltSelCode; int256 hltVarCode; /// other scene colors int256[3] lightCol; int256[3] bgColTop; int256[3] bgColBottom; } /** @dev calculate the color of a prism returns an array of 6 colors (for each vertex of a prism) */ function getColForPrism( bytes32 tokenHash, int256[3][3] memory triFront, SubScheme memory subScheme, int256[3][2] memory extents ) external view returns (int256[3][6] memory cols) { if ( subScheme.colA[0] == subScheme.colB[0] && subScheme.colA[1] == subScheme.colB[1] && subScheme.colA[2] == subScheme.colB[2] ) { /// just use color A (as B is the same, so there's no gradient) for (uint256 i = 0; i < 6; i++) { cols[i] = copyColor(subScheme.colA); } } else { /// get the colors according to the direction code int256[3][3] memory triFrontCopy = GeomUtils.copyTri(triFront); int256[3][3] memory frontTriCols = applyDirHelp( triFrontCopy, subScheme.colA, subScheme.colB, subScheme.dirCode, subScheme.isInnerGradient, extents ); /// write in the same front colors as the back colors for (uint256 i = 0; i < 3; i++) { cols[i] = copyColor(frontTriCols[i]); cols[i + 3] = copyColor(frontTriCols[i]); } } /// perform the jiggling int256[3] memory jiggle; if (!subScheme.isJiggleInner) { /// get one set of jiggle values to use for all colors created jiggle = getJiggle(subScheme.jiggle, tokenHash, 0); } for (uint256 i = 0; i < 6; i++) { if (subScheme.isJiggleInner) { // jiggle again per col to create // use the last jiggle res in the random seed to get diff jiggles for each prism jiggle = getJiggle(subScheme.jiggle, tokenHash, jiggle[0]); } /// convert to hsv prior to jiggle int256[3] memory colHsv = rgb2hsv( cols[i][0], cols[i][1], cols[i][2] ); /// add the jiggle to the colors in hsv space colHsv[0] = colHsv[0] + jiggle[0]; colHsv[1] = colHsv[1] + jiggle[1]; colHsv[2] = colHsv[2] + jiggle[2]; /// convert back to rgb int256[3] memory colRgb = hsv2rgb(colHsv[0], colHsv[1], colHsv[2]); cols[i][0] = colRgb[0]; cols[i][1] = colRgb[1]; cols[i][2] = colRgb[2]; } /// perform back shifting for (uint256 i = 0; i < 3; i++) { cols[i][0] -= subScheme.backShift[0]; cols[i][1] -= subScheme.backShift[1]; cols[i][2] -= subScheme.backShift[2]; } /// ensure that we're in 255 range for (uint256 i = 0; i < 6; i++) { cols[i][0] = ShackledMath.max(0, ShackledMath.min(255, cols[i][0])); cols[i][1] = ShackledMath.max(0, ShackledMath.min(255, cols[i][1])); cols[i][2] = ShackledMath.max(0, ShackledMath.min(255, cols[i][2])); } return cols; } /** @dev roll a schemeId given a list of weightings */ function getSchemeId(bytes32 tokenHash, int256[2][10] memory weightings) internal view returns (uint256) { int256 n = GeomUtils.randN( tokenHash, "schemedId", weightings[0][0], weightings[weightings.length - 1][1] ); for (uint256 i = 0; i < weightings.length; i++) { if (weightings[i][0] <= n && n <= weightings[i][1]) { return i; } } } /** @dev make a copy of a color */ function copyColor(int256[3] memory c) internal view returns (int256[3] memory) { return [c[0], c[1], c[2]]; } /** @dev get a color scheme */ function getScheme(bytes32 tokenHash, int256[3][3][] memory tris) external view returns (ColScheme memory colScheme) { /// 'randomly' select 1 of the 9 schemes uint256 schemeId = getSchemeId( tokenHash, [ [int256(0), 1500], [int256(1500), 2500], [int256(2500), 3000], [int256(3000), 3100], [int256(3100), 5500], [int256(5500), 6000], [int256(6000), 6500], [int256(6500), 8000], [int256(8000), 9500], [int256(9500), 10000] ] ); // int256 schemeId = GeomUtils.randN(tokenHash, "schemeID", 1, 9); /// define the color scheme to use for this piece /// all arrays are on the order of 1000 to remain accurate as integers /// will require division by 1000 later when in use if (schemeId == 0) { /// plain / beigey with a highlight, and a matching background colour colScheme = ColScheme({ name: "Accentuated", id: schemeId, pri: SubScheme({ colA: [int256(60), 30, 25], colB: [int256(205), 205, 205], isInnerGradient: false, dirCode: 0, jiggle: [int256(13), 13, 13], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [int256(255), 0, 0], colB: [int256(255), 50, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code jiggle: [int256(50), 50, 50], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 3, 5)), /// get a 'random' number of highlights between 3 and 5 hltSelCode: 1, /// 'biggest' selection code hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(1), 1, 1] }); } else if (schemeId == 1) { /// neutral overall colScheme = ColScheme({ name: "Emergent", id: schemeId, pri: SubScheme({ colA: [int256(0), 77, 255], colB: [int256(0), 255, 25], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "priDir", 2, 3), /// get a 'random' dir code (2 or 3) jiggle: [int256(60), 60, 60], isJiggleInner: false, backShift: [int256(-255), -255, -255] }), hlt: SubScheme({ colA: [int256(0), 77, 255], colB: [int256(0), 255, 25], isInnerGradient: true, dirCode: 3, jiggle: [int256(60), 60, 60], isJiggleInner: false, backShift: [int256(-255), -255, -255] }), hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 4, 6)), /// get a 'random' number of highlights between 4 and 6 hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(255), 255, 255], bgColBottom: [int256(255), 255, 255] }); } else if (schemeId == 2) { /// vaporwave int256 maxHighlights = ShackledMath.max(0, int256(tris.length) - 8); int256 minHighlights = ShackledMath.max( 0, int256(maxHighlights) - 2 ); colScheme = ColScheme({ name: "Sunset", id: schemeId, pri: SubScheme({ colA: [int256(179), 0, 179], colB: [int256(0), 0, 255], isInnerGradient: false, dirCode: 2, /// up-down jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: [int256(0), 0, 0], colB: [int256(0), 0, 0], isInnerGradient: true, dirCode: 3, /// down-up jiggle: [int256(15), 0, 15], isJiggleInner: true, backShift: [int256(0), 0, 0] }), hltNum: uint256( GeomUtils.randN( tokenHash, "hltNum", minHighlights, maxHighlights ) ), /// get a 'random' number of highlights between minHighlights and maxHighlights hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(250), 103, 247], bgColBottom: [int256(157), 104, 250] }); } else if (schemeId == 3) { /// gold int256 priDirCode = GeomUtils.randN(tokenHash, "pirDir", 0, 1); /// get a 'random' dir code (0 or 1) colScheme = ColScheme({ name: "Stone & Gold", id: schemeId, pri: SubScheme({ colA: [int256(50), 50, 50], colB: [int256(100), 100, 100], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(10), 10, 10], isJiggleInner: true, backShift: [int256(128), 128, 128] }), hlt: SubScheme({ colA: [int256(255), 197, 0], colB: [int256(255), 126, 0], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(64), 64, 64] }), hltNum: 1, hltSelCode: 1, /// biggest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 4) { /// random pastel colors (sometimes black) /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Denatured", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: false, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 1), /// get a 'random' dir code (0 or 1) jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: false, dirCode: GeomUtils.randN(tokenHash, "hlt", 0, 1), /// get a 'random' dir code (0 or 1) jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(127), 127, 127] }), hltNum: tris.length / 2, hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 5) { /// inter triangle random colors ('chameleonic') /// pri dir code is anything (0, 1, 2, 3) /// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du) int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 3); /// get a 'random' dir code (0 or 1) int256 hltDirCode; if (priDirCode == 0 || priDirCode == 1) { hltDirCode = priDirCode == 0 ? int256(1) : int256(0); } else { hltDirCode = priDirCode == 2 ? int256(3) : int256(2); } /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Chameleonic", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(0), 0, 0] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: true, dirCode: hltDirCode, jiggle: [int256(255), 255, 255], isJiggleInner: true, backShift: [int256(205), 205, 205] }), hltNum: 12, hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 6) { /// each prism is a different colour with some randomisation /// pri dir code is anything (0, 1, 2, 3) /// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du) int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 1); /// get a 'random' dir code (0 or 1) int256 hltDirCode; if (priDirCode == 0 || priDirCode == 1) { hltDirCode = priDirCode == 0 ? int256(1) : int256(0); } else { hltDirCode = priDirCode == 2 ? int256(3) : int256(2); } /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Gradiated", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: false, dirCode: priDirCode, jiggle: [int256(127), 127, 127], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: false, dirCode: hltDirCode, jiggle: [int256(127), 127, 127], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: 12, /// get a 'random' number of highlights between 4 and 6 hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 7) { /// feature colour on white primary, with feature colour background /// calculate the feature color in hsv int256[3] memory hsv = [ GeomUtils.randN(tokenHash, "hsv", 0, 255), 230, 255 ]; int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]); colScheme = ColScheme({ name: "Vivid Alabaster", id: schemeId, pri: SubScheme({ colA: [int256(255), 255, 255], colB: [int256(255), 255, 255], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1) jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: hltColA, colB: copyColor(hltColA), /// same as A isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode jiggle: [int256(25), 50, 50], isJiggleInner: true, backShift: [int256(180), 180, 180] }), hltNum: tris.length % 2 == 1 ? (tris.length / 2) + 1 : tris.length / 2, hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2), hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: hsv2rgb( ShackledMath.mod((hsv[0] - 9), 255), 105, 255 ), bgColBottom: hsv2rgb( ShackledMath.mod((hsv[0] + 9), 255), 105, 255 ) }); } else if (schemeId == 8) { /// feature colour on black primary, with feature colour background /// calculate the feature color in hsv int256[3] memory hsv = [ GeomUtils.randN(tokenHash, "hsv", 0, 255), 245, 190 ]; int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]); colScheme = ColScheme({ name: "Vivid Ink", id: schemeId, pri: SubScheme({ colA: [int256(0), 0, 0], colB: [int256(0), 0, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1) jiggle: [int256(25), 25, 25], isJiggleInner: false, backShift: [int256(-60), -60, -60] }), hlt: SubScheme({ colA: hltColA, colB: copyColor(hltColA), /// same as A isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(-60), -60, -60] }), hltNum: tris.length % 2 == 1 ? (tris.length / 2) + 1 : tris.length / 2, hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2), hltVarCode: GeomUtils.randN(tokenHash, "hltVar", 0, 2), lightCol: [int256(255), 255, 255], bgColTop: hsv2rgb( ShackledMath.mod((hsv[0] - 9), 255), 105, 255 ), bgColBottom: hsv2rgb( ShackledMath.mod((hsv[0] + 9), 255), 105, 255 ) }); } else if (schemeId == 9) { colScheme = ColScheme({ name: "Pigmented", id: schemeId, pri: SubScheme({ colA: [int256(50), 30, 25], colB: [int256(205), 205, 205], isInnerGradient: false, dirCode: 0, jiggle: [int256(13), 13, 13], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [int256(255), 0, 0], colB: [int256(255), 50, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code jiggle: [int256(255), 50, 50], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: tris.length / 3, hltSelCode: 1, /// 'biggest' selection code hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(7), 7, 7] }); } else { revert("invalid scheme id"); } return colScheme; } /** @dev convert hsv to rgb color assume h, s and v and in range [0, 255] outputs rgb in range [0, 255] */ function hsv2rgb( int256 h, int256 s, int256 v ) internal view returns (int256[3] memory res) { /// ensure range 0, 255 h = ShackledMath.max(0, ShackledMath.min(255, h)); s = ShackledMath.max(0, ShackledMath.min(255, s)); v = ShackledMath.max(0, ShackledMath.min(255, v)); int256 h2 = (((h % 255) * 1e3) / 255) * 360; /// convert to degress int256 v2 = (v * 1e3) / 255; int256 s2 = (s * 1e3) / 255; /// calculate c, x and m while scaling all by 1e3 /// otherwise x will be too small and round to 0 int256 c = (v2 * s2) / 1e3; int256 x = (c * (1 * 1e3 - ShackledMath.abs(((h2 / 60) % (2 * 1e3)) - (1 * 1e3)))); x = x / 1e3; int256 m = v2 - c; if (0 <= h2 && h2 < 60000) { res = [c + m, x + m, m]; } else if (60000 <= h2 && h2 < 120000) { res = [x + m, c + m, m]; } else if (120000 < h2 && h2 < 180000) { res = [m, c + m, x + m]; } else if (180000 < h2 && h2 < 240000) { res = [m, x + m, c + m]; } else if (240000 < h2 && h2 < 300000) { res = [x + m, m, c + m]; } else if (300000 < h2 && h2 < 360000) { res = [c + m, m, x + m]; } else { res = [int256(0), 0, 0]; } /// scale into correct range return [ (res[0] * 255) / 1e3, (res[1] * 255) / 1e3, (res[2] * 255) / 1e3 ]; } /** @dev convert rgb to hsv expects rgb to be in range [0, 255] outputs hsv in range [0, 255] */ function rgb2hsv( int256 r, int256 g, int256 b ) internal view returns (int256[3] memory) { int256 r2 = (r * 1e3) / 255; int256 g2 = (g * 1e3) / 255; int256 b2 = (b * 1e3) / 255; int256 max = ShackledMath.max(ShackledMath.max(r2, g2), b2); int256 min = ShackledMath.min(ShackledMath.min(r2, g2), b2); int256 delta = max - min; /// calculate hue int256 h; if (delta != 0) { if (max == r2) { int256 _h = ((g2 - b2) * 1e3) / delta; h = 60 * ShackledMath.mod(_h, 6000); } else if (max == g2) { h = 60 * (((b2 - r2) * 1e3) / delta + (2000)); } else if (max == b2) { h = 60 * (((r2 - g2) * 1e3) / delta + (4000)); } } h = (h % (360 * 1e3)) / 360; /// calculate saturation int256 s; if (max != 0) { s = (delta * 1e3) / max; } /// calculate value int256 v = max; return [(h * 255) / 1e3, (s * 255) / 1e3, (v * 255) / 1e3]; } /** @dev get vector of three numbers that can be used to jiggle a color */ function getJiggle( int256[3] memory jiggle, bytes32 randomSeed, int256 seedModifier ) internal view returns (int256[3] memory) { return [ jiggle[0] + GeomUtils.randN( randomSeed, string(abi.encodePacked("0", seedModifier)), -jiggle[0], jiggle[0] ), jiggle[1] + GeomUtils.randN( randomSeed, string(abi.encodePacked("1", seedModifier)), -jiggle[1], jiggle[1] ), jiggle[2] + GeomUtils.randN( randomSeed, string(abi.encodePacked("2", seedModifier)), -jiggle[2], jiggle[2] ) ]; } /** @dev check if a uint is in an array */ function inArray(uint256[] memory array, uint256 value) external view returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } /** @dev a helper function to apply the direction code in interpolation */ function applyDirHelp( int256[3][3] memory triFront, int256[3] memory colA, int256[3] memory colB, int256 dirCode, bool isInnerGradient, int256[3][2] memory extents ) internal view returns (int256[3][3] memory triCols) { uint256[3] memory order; if (isInnerGradient) { /// perform the simple 3 sort - always color by the front order = getOrderedPointIdxsInDir(triFront, dirCode); } else { /// order irrelevant in other case order = [uint256(0), 1, 2]; } /// axis is 0 (horizontal) if dir code is left-right or right-left /// 1 (vertical) otherwise uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1; int256 length; if (axis == 0) { length = extents[1][0] - extents[0][0]; } else { length = extents[1][1] - extents[0][1]; } /// if we're interpolating across the triangle (inner) /// then do so by calculating the color at each point in the triangle for (uint256 i = 0; i < 3; i++) { triCols[order[i]] = interpColHelp( colA, colB, (isInnerGradient) ? triFront[order[0]][axis] : int256(-length / 2), (isInnerGradient) ? triFront[order[2]][axis] : int256(length / 2), triFront[order[i]][axis] ); } } /** @dev a helper function to order points by index in a desired direction */ function getOrderedPointIdxsInDir(int256[3][3] memory tri, int256 dirCode) internal view returns (uint256[3] memory) { // flip if dir is left-right or down-up bool flip = (dirCode == 1 || dirCode == 3) ? true : false; // axis is 0 if horizontal (left-right or right-left), 1 otherwise (vertical) uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1; /// get the values of each point in the tri (flipped as required) int256 f = (flip) ? int256(-1) : int256(1); int256 a = f * tri[0][axis]; int256 b = f * tri[1][axis]; int256 c = f * tri[2][axis]; /// get the ordered indices uint256[3] memory ixOrd = [uint256(0), 1, 2]; /// simplest way to sort 3 numbers if (a > b) { (a, b) = (b, a); (ixOrd[0], ixOrd[1]) = (ixOrd[1], ixOrd[0]); } if (a > c) { (a, c) = (c, a); (ixOrd[0], ixOrd[2]) = (ixOrd[2], ixOrd[0]); } if (b > c) { (b, c) = (c, b); (ixOrd[1], ixOrd[2]) = (ixOrd[2], ixOrd[1]); } return ixOrd; } /** @dev a helper function for linear interpolation betweet two colors*/ function interpColHelp( int256[3] memory colA, int256[3] memory colB, int256 low, int256 high, int256 val ) internal view returns (int256[3] memory result) { int256 ir; int256 lerpScaleFactor = 1e3; if (high - low == 0) { ir = 1; } else { ir = ((val - low) * lerpScaleFactor) / (high - low); } for (uint256 i = 0; i < 3; i++) { /// dont allow interpolation to go below 0 result[i] = ShackledMath.max( 0, colA[i] + ((colB[i] - colA[i]) * ir) / lerpScaleFactor ); } } /** @dev get indexes of the prisms to use highlight coloring*/ function getHighlightPrismIdxs( int256[3][3][] memory tris, bytes32 tokenHash, uint256 nHighlights, int256 varCode, int256 selCode ) internal view returns (uint256[] memory idxs) { nHighlights = nHighlights < tris.length ? nHighlights : tris.length; ///if we just want random triangles then there's no need to sort if (selCode == 0) { idxs = ShackledMath.randomIdx( tokenHash, uint256(nHighlights), tris.length - 1 ); } else { idxs = getSortedTrisIdxs(tris, nHighlights, varCode, selCode); } } /** @dev return the index of the tris sorted by sel code @param selCode will be 1 (biggest first) or 2 (smallest first) */ function getSortedTrisIdxs( int256[3][3][] memory tris, uint256 nHighlights, int256 varCode, int256 selCode ) internal view returns (uint256[] memory) { // determine the sort order int256 orderFactor = (selCode == 2) ? int256(1) : int256(-1); /// get the list of triangle sizes int256[] memory sizes = new int256[](tris.length); for (uint256 i = 0; i < tris.length; i++) { if (varCode == 0) { // use size sizes[i] = GeomUtils.getRadiusLen(tris[i]) * orderFactor; } else if (varCode == 1) { // use x sizes[i] = GeomUtils.getCenterVec(tris[i])[0] * orderFactor; } else if (varCode == 2) { // use y sizes[i] = GeomUtils.getCenterVec(tris[i])[1] * orderFactor; } } /// initialise the index array uint256[] memory idxs = new uint256[](tris.length); for (uint256 i = 0; i < tris.length; i++) { idxs[i] = i; } /// run a boilerplate insertion sort over the index array for (uint256 i = 1; i < tris.length; i++) { int256 key = sizes[i]; uint256 j = i - 1; while (j > 0 && key < sizes[j]) { sizes[j + 1] = sizes[j]; idxs[j + 1] = idxs[j]; j--; } sizes[j + 1] = key; idxs[j + 1] = i; } uint256 nToCull = tris.length - nHighlights; assembly { mstore(idxs, sub(mload(idxs), nToCull)) } return idxs; } } /** Hold some functions externally to reduce contract size for mainnet deployment */ library GeomUtils { /// misc constants int256 constant MIN_INT = type(int256).min; int256 constant MAX_INT = type(int256).max; /// constants for doing trig int256 constant PI = 3141592653589793238; // pi as an 18 decimal value (wad) /// parameters that control geometry creation struct GeomSpec { string name; int256 id; int256 forceInitialSize; uint256 maxPrisms; int256 minTriRad; int256 maxTriRad; bool varySize; int256 depthMultiplier; bool isSymmetricX; bool isSymmetricY; int256 probVertOpp; int256 probAdjRec; int256 probVertOppRec; } /// variables uses when creating the initial 2d triangles struct TriVars { uint256 nextTriIdx; int256[3][3][] tris; int256[3][3] tri; int256 zBackRef; int256 zFrontRef; int256[] zFronts; int256[] zBacks; bool recursiveAttempt; } /// variables used when creating 3d prisms struct GeomVars { int256 rotX; int256 rotY; int256 rotZ; int256[3][2] extents; int256[3] center; int256 width; int256 height; int256 extent; int256 scaleNum; uint256[] hltPrismIdx; int256[3][3][] trisBack; int256[3][3][] trisFront; uint256 nPrisms; } /** @dev generate parameters that will control how the geometry is built */ function generateSpec(bytes32 tokenHash) external view returns (GeomSpec memory spec) { // 'randomly' select 1 of possible geometry specifications uint256 specId = getSpecId( tokenHash, [ [int256(0), 1000], [int256(1000), 3000], [int256(3000), 3500], [int256(3500), 4500], [int256(4500), 5000], [int256(5000), 6000], [int256(6000), 8000] ] ); bool isSymmetricX = GeomUtils.randN(tokenHash, "symmX", 0, 2) > 0; bool isSymmetricY = GeomUtils.randN(tokenHash, "symmY", 0, 2) > 0; int256 defaultDepthMultiplier = randN(tokenHash, "depthMult", 80, 120); int256 defaultMinTriRad = 4800; int256 defaultMaxTriRad = defaultMinTriRad * 3; uint256 defaultMaxPrisms = uint256( randN(tokenHash, "maxPrisms", 8, 16) ); if (specId == 0) { /// all vertically opposite spec = GeomSpec({ id: 0, name: "Verticalized", forceInitialSize: (defaultMinTriRad * 5) / 2, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 100, probVertOppRec: 100, probAdjRec: 0, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 1) { /// fully adjacent spec = GeomSpec({ id: 1, name: "Adjoint", forceInitialSize: (defaultMinTriRad * 5) / 2, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 0, probVertOppRec: 0, probAdjRec: 100, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 2) { /// few but big spec = GeomSpec({ id: 2, name: "Cetacean", forceInitialSize: 0, maxPrisms: 8, minTriRad: defaultMinTriRad * 3, maxTriRad: defaultMinTriRad * 4, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 3) { /// lots but small spec = GeomSpec({ id: 3, name: "Swarm", forceInitialSize: 0, maxPrisms: 16, minTriRad: defaultMinTriRad, maxTriRad: defaultMinTriRad * 2, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 0, probAdjRec: 0, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 4) { /// all same size spec = GeomSpec({ id: 4, name: "Isomorphic", forceInitialSize: 0, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: false, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 5) { /// trains spec = GeomSpec({ id: 5, name: "Extruded", forceInitialSize: 0, maxPrisms: 10, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 6) { /// flatpack spec = GeomSpec({ id: 6, name: "Uniform", forceInitialSize: 0, maxPrisms: 12, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else { revert("invalid specId"); } } /** @dev make triangles to the side of a reference triangle */ function makeAdjacentTriangles( bytes32 tokenHash, uint256 attemptNum, uint256 refIdx, TriVars memory triVars, GeomSpec memory geomSpec, int256 overrideSideIdx, int256 overrideScale, int256 depth ) public view returns (TriVars memory) { /// get the side index (0, 1 or 2) int256 sideIdx; if (overrideSideIdx == -1) { sideIdx = randN( tokenHash, string(abi.encodePacked("sideIdx", attemptNum, depth)), 0, 2 ); } else { sideIdx = overrideSideIdx; } /// get the scale /// this value is scaled up by 1e3 (desired range is 0.333 to 0.8) /// the scale will be divided out when used int256 scale; if (geomSpec.varySize) { if (overrideScale == -1) { scale = randN( tokenHash, string(abi.encodePacked("scaleAdj", attemptNum, depth)), 333, 800 ); } else { scale = overrideScale; } } else { scale = 1e3; } /// make a new triangle int256[3][3] memory newTri = makeTriAdjacent( tokenHash, geomSpec, attemptNum, triVars.tris[refIdx], sideIdx, scale, depth ); /// set the zbackref and frontbackref triVars.zBackRef = -1; /// calculate a new z back triVars.zFrontRef = -1; /// calculate a new z ftont // try to add the triangle, and use the reference z height triVars.recursiveAttempt = false; bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec); if (wasAdded) { // run again if ( randN( tokenHash, string( abi.encodePacked("addAdjRecursive", attemptNum, depth) ), 0, 100 ) <= geomSpec.probAdjRec ) { triVars = makeAdjacentTriangles( tokenHash, attemptNum, triVars.nextTriIdx - 1, triVars, geomSpec, sideIdx, 666, /// always make the next one 2/3 scale depth + 1 ); } } return triVars; } /** @dev make triangles vertically opposite a reference triangle */ function makeVerticallyOppositeTriangles( bytes32 tokenHash, uint256 attemptNum, uint256 refIdx, TriVars memory triVars, GeomSpec memory geomSpec, int256 overrideSideIdx, int256 overrideScale, int256 depth ) public view returns (TriVars memory) { /// get the side index (0, 1 or 2) int256 sideIdx; if (overrideSideIdx == -1) { sideIdx = randN( tokenHash, string(abi.encodePacked("vertOppSideIdx", attemptNum, depth)), 0, 2 ); } else { sideIdx = overrideSideIdx; } /// get the scale /// this value is scaled up by 1e3 /// use attemptNum in seedModifier to ensure unique values each attempt int256 scale; if (geomSpec.varySize) { if (overrideScale == -1) { if ( // prettier-ignore randN( tokenHash, string(abi.encodePacked("vertOppScale1", attemptNum, depth)), 0, 100 ) > 33 ) { // prettier-ignore if ( randN( tokenHash, string(abi.encodePacked("vertOppScale2", attemptNum, depth) ), 0, 100 ) > 50 ) { scale = 1000; /// desired = 1 (same scale) } else { scale = 500; /// desired = 0.5 (half scale) } } else { scale = 2000; /// desired = 2 (double scale) } } else { scale = overrideScale; } } else { scale = 1e3; } /// make a new triangle int256[3][3] memory newTri = makeTriVertOpp( triVars.tris[refIdx], geomSpec, sideIdx, scale ); /// set the zbackref and frontbackref triVars.zBackRef = -1; /// calculate a new z back triVars.zFrontRef = triVars.zFronts[refIdx]; // try to add the triangle, and use the reference z height triVars.recursiveAttempt = false; bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec); if (wasAdded) { /// run again if ( randN( tokenHash, string( abi.encodePacked("recursiveVertOpp", attemptNum, depth) ), 0, 100 ) <= geomSpec.probVertOppRec ) { triVars = makeVerticallyOppositeTriangles( tokenHash, attemptNum, refIdx, triVars, geomSpec, sideIdx, 666, /// always make the next one 2/3 scale depth + 1 ); } } return triVars; } /** @dev place a triangle vertically opposite over the given point @param refTri the reference triangle to base the new triangle on */ function makeTriVertOpp( int256[3][3] memory refTri, GeomSpec memory geomSpec, int256 sideIdx, int256 scale ) internal view returns (int256[3][3] memory) { /// calculate the center of the reference triangle /// add and then divide by 1e3 (the factor by which scale is scaled up) int256 centerDist = (getRadiusLen(refTri) * (1e3 + scale)) / 1e3; /// get the new triangle's direction int256 newAngle = sideIdx * 120 + 60 + (isTriPointingUp(refTri) ? int256(60) : int256(0)); int256 spacing = 64; /// calculate the true offset int256[3] memory offset = vector3RotateZ( [int256(0), centerDist + spacing, 0], newAngle ); int256[3] memory centerVec = getCenterVec(refTri); int256[3] memory newCentre = ShackledMath.vector3Add(centerVec, offset); /// return the new triangle (div by 1e3 to account for scale) int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3; newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius); newAngle -= 210; return makeTri(newCentre, newRadius, newAngle); } /** @dev make a new adjacent triangle */ function makeTriAdjacent( bytes32 tokenHash, GeomSpec memory geomSpec, uint256 attemptNum, int256[3][3] memory refTri, int256 sideIdx, int256 scale, int256 depth ) internal view returns (int256[3][3] memory) { /// calculate the center of the new triangle /// add and then divide by 1e3 (the factor by which scale is scaled up) int256 centerDist = (getPerpLen(refTri) * (1e3 + scale)) / 1e3; /// get the new triangle's direction int256 newAngle = sideIdx * 120 + (isTriPointingUp(refTri) ? int256(60) : int256(0)); /// determine the direction of the offset offset /// get a unique random seed each attempt to ensure variation // prettier-ignore int256 offsetDirection = randN( tokenHash, string(abi.encodePacked("lateralOffset", attemptNum, depth)), 0, 1 ) * 2 - 1; /// put if off to one side of the triangle if it's smaller /// scale is on order of 1e3 int256 lateralOffset = (offsetDirection * (1e3 - scale) * getSideLen(refTri)) / 1e3; /// make a gap between the triangles int256 spacing = 6000; /// calculate the true offset int256[3] memory offset = vector3RotateZ( [lateralOffset, centerDist + spacing, 0], newAngle ); int256[3] memory newCentre = ShackledMath.vector3Add( getCenterVec(refTri), offset ); /// return the new triangle (div by 1e3 to account for scale) int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3; newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius); newAngle -= 30; return makeTri(newCentre, newRadius, newAngle); } /** @dev create a triangle centered at centre, with length from centre to point of radius */ function makeTri( int256[3] memory centre, int256 radius, int256 angle ) internal view returns (int256[3][3] memory tri) { /// create a vector to rotate around 3 times int256[3] memory offset = [radius, 0, 0]; /// make 3 points of the tri for (uint256 i = 0; i < 3; i++) { int256 armAngle = 120 * int256(i); int256[3] memory offsetVec = vector3RotateZ( offset, armAngle + angle ); tri[i] = ShackledMath.vector3Add(centre, offsetVec); } } /** @dev rotate a vector around x */ function vector3RotateX(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new y and z (scaling down to account for trig scaling) int256 y = ((v[1] * cos) - (v[2] * sin)) / 1e18; int256 z = ((v[1] * sin) + (v[2] * cos)) / 1e18; return [v[0], y, z]; } /** @dev rotate a vector around y */ function vector3RotateY(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new x and z (scaling down to account for trig scaling) int256 x = ((v[0] * cos) - (v[2] * sin)) / 1e18; int256 z = ((v[0] * sin) + (v[2] * cos)) / 1e18; return [x, v[1], z]; } /** @dev rotate a vector around z */ function vector3RotateZ(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new x and y (scaling down to account for trig scaling) int256 x = ((v[0] * cos) - (v[1] * sin)) / 1e18; int256 y = ((v[0] * sin) + (v[1] * cos)) / 1e18; return [x, y, v[2]]; } /** @dev calculate sin and cos of an angle */ function trigHelper(int256 deg) internal view returns (int256 cos, int256 sin) { /// deal with negative degrees here, since Trigonometry.sol can't int256 n360 = (ShackledMath.abs(deg) / 360) + 1; deg = (deg + (360 * n360)) % 360; uint256 rads = uint256((deg * PI) / 180); /// calculate radians (in 1e18 space) cos = Trigonometry.cos(rads); sin = Trigonometry.sin(rads); } /** @dev Get the 3d vector at the center of a triangle */ function getCenterVec(int256[3][3] memory tri) internal view returns (int256[3] memory) { return ShackledMath.vector3DivScalar( ShackledMath.vector3Add( ShackledMath.vector3Add(tri[0], tri[1]), tri[2] ), 3 ); } /** @dev Get the length from the center of a triangle to point*/ function getRadiusLen(int256[3][3] memory tri) internal view returns (int256) { return ShackledMath.vector3Len( ShackledMath.vector3Sub(getCenterVec(tri), tri[0]) ); } /** @dev Get the length from any point on triangle to other point (equilateral)*/ function getSideLen(int256[3][3] memory tri) internal view returns (int256) { // len * 0.886 return (getRadiusLen(tri) * 8660) / 10000; } /** @dev Get the shortes length from center of triangle to side */ function getPerpLen(int256[3][3] memory tri) internal view returns (int256) { return getRadiusLen(tri) / 2; } /** @dev Determine if a triangle is pointing up*/ function isTriPointingUp(int256[3][3] memory tri) internal view returns (bool) { int256 centerY = getCenterVec(tri)[1]; /// count how many verts are above this y value int256 nAbove = 0; for (uint256 i = 0; i < 3; i++) { if (tri[i][1] > centerY) { nAbove++; } } return nAbove == 1; } /** @dev check if two triangles are close */ function areTrisClose(int256[3][3] memory tri1, int256[3][3] memory tri2) internal view returns (bool) { int256 lenBetweenCenters = ShackledMath.vector3Len( ShackledMath.vector3Sub(getCenterVec(tri1), getCenterVec(tri2)) ); return lenBetweenCenters < (getPerpLen(tri1) + getPerpLen(tri2)); } /** @dev check if two triangles have overlapping points*/ function areTrisPointsOverlapping( int256[3][3] memory tri1, int256[3][3] memory tri2 ) internal view returns (bool) { /// check triangle a against b if ( isPointInTri(tri1, tri2[0]) || isPointInTri(tri1, tri2[1]) || isPointInTri(tri1, tri2[2]) ) { return true; } /// check triangle b against a if ( isPointInTri(tri2, tri1[0]) || isPointInTri(tri2, tri1[1]) || isPointInTri(tri2, tri1[2]) ) { return true; } /// otherwise they mustn't be overlapping return false; } /** @dev calculate if a point is in a tri*/ function isPointInTri(int256[3][3] memory tri, int256[3] memory p) internal view returns (bool) { int256[3] memory p1 = tri[0]; int256[3] memory p2 = tri[1]; int256[3] memory p3 = tri[2]; int256 alphaNum = (p2[1] - p3[1]) * (p[0] - p3[0]) + (p3[0] - p2[0]) * (p[1] - p3[1]); int256 alphaDenom = (p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]); int256 betaNum = (p3[1] - p1[1]) * (p[0] - p3[0]) + (p1[0] - p3[0]) * (p[1] - p3[1]); int256 betaDenom = (p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]); if (alphaDenom == 0 || betaDenom == 0) { return false; } else { int256 alpha = (alphaNum * 1e6) / alphaDenom; int256 beta = (betaNum * 1e6) / betaDenom; int256 gamma = 1e6 - alpha - beta; return alpha > 0 && beta > 0 && gamma > 0; } } /** @dev check all points of the tri to see if it overlaps with any other tris */ function isTriOverlappingWithTris( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx ) internal view returns (bool) { /// check against all other tris added thus fat for (uint256 i = 0; i < nextTriIdx; i++) { if ( areTrisClose(tri, tris[i]) || areTrisPointsOverlapping(tri, tris[i]) ) { return true; } } return false; } function isPointCloseToLine( int256[3] memory p, int256[3] memory l1, int256[3] memory l2 ) internal view returns (bool) { int256 x0 = p[0]; int256 y0 = p[1]; int256 x1 = l1[0]; int256 y1 = l1[1]; int256 x2 = l2[0]; int256 y2 = l2[1]; int256 distanceNum = ShackledMath.abs( (x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1) ); int256 distanceDenom = ShackledMath.hypot((x2 - x1), (y2 - y1)); int256 distance = distanceNum / distanceDenom; if (distance < 8) { return true; } } /** compare a triangles points against the lines of other tris */ function isTrisPointsCloseToLines( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx ) internal view returns (bool) { for (uint256 i = 0; i < nextTriIdx; i++) { for (uint256 p = 0; p < 3; p++) { if (isPointCloseToLine(tri[p], tris[i][0], tris[i][1])) { return true; } if (isPointCloseToLine(tri[p], tris[i][1], tris[i][2])) { return true; } if (isPointCloseToLine(tri[p], tris[i][2], tris[i][0])) { return true; } } } } /** @dev check if tri to add meets certain criteria */ function isTriLegal( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx, int256 minTriRad ) internal view returns (bool) { // check radius first as point checks will fail // if the radius is too small if (getRadiusLen(tri) < minTriRad) { return false; } return (!isTriOverlappingWithTris(tri, tris, nextTriIdx) && !isTrisPointsCloseToLines(tri, tris, nextTriIdx)); } /** @dev helper function to add triangles */ function attemptToAddTri( int256[3][3] memory tri, bytes32 tokenHash, TriVars memory triVars, GeomSpec memory geomSpec ) internal view returns (bool added) { bool isLegal = isTriLegal( tri, triVars.tris, triVars.nextTriIdx, geomSpec.minTriRad ); if (isLegal && triVars.nextTriIdx < geomSpec.maxPrisms) { // add the triangle triVars.tris[triVars.nextTriIdx] = tri; added = true; // add the new zs if (triVars.zBackRef == -1) { /// z back ref is not provided, calculate it triVars.zBacks[triVars.nextTriIdx] = calculateZ( tri, tokenHash, triVars.nextTriIdx, geomSpec, false ); } else { /// use the provided z back (from the ref) triVars.zBacks[triVars.nextTriIdx] = triVars.zBackRef; } if (triVars.zFrontRef == -1) { /// z front ref is not provided, calculate it triVars.zFronts[triVars.nextTriIdx] = calculateZ( tri, tokenHash, triVars.nextTriIdx, geomSpec, true ); } else { /// use the provided z front (from the ref) triVars.zFronts[triVars.nextTriIdx] = triVars.zFrontRef; } // increment the tris counter triVars.nextTriIdx += 1; // if we're using any type of symmetry then attempt to add a symmetric triangle // only do this recursively once if ( (geomSpec.isSymmetricX || geomSpec.isSymmetricY) && (!triVars.recursiveAttempt) ) { int256[3][3] memory symTri = copyTri(tri); if (geomSpec.isSymmetricX) { symTri[0][0] = -symTri[0][0]; symTri[1][0] = -symTri[1][0]; symTri[2][0] = -symTri[2][0]; // symCenter[0] = -symCenter[0]; } if (geomSpec.isSymmetricY) { symTri[0][1] = -symTri[0][1]; symTri[1][1] = -symTri[1][1]; symTri[2][1] = -symTri[2][1]; // symCenter[1] = -symCenter[1]; } if ( (geomSpec.isSymmetricX || geomSpec.isSymmetricY) && !(geomSpec.isSymmetricX && geomSpec.isSymmetricY) ) { symTri = [symTri[2], symTri[1], symTri[0]]; } triVars.recursiveAttempt = true; triVars.zBackRef = triVars.zBacks[triVars.nextTriIdx - 1]; triVars.zFrontRef = triVars.zFronts[triVars.nextTriIdx - 1]; attemptToAddTri(symTri, tokenHash, triVars, geomSpec); } } } /** @dev rotate a triangle by x, y, or z @param axis 0 = x, 1 = y, 2 = z */ function triRotHelp( int256 axis, int256[3][3] memory tri, int256 rot ) internal view returns (int256[3][3] memory) { if (axis == 0) { return [ vector3RotateX(tri[0], rot), vector3RotateX(tri[1], rot), vector3RotateX(tri[2], rot) ]; } else if (axis == 1) { return [ vector3RotateY(tri[0], rot), vector3RotateY(tri[1], rot), vector3RotateY(tri[2], rot) ]; } else if (axis == 2) { return [ vector3RotateZ(tri[0], rot), vector3RotateZ(tri[1], rot), vector3RotateZ(tri[2], rot) ]; } } /** @dev a helper to run rotation functions on back/front triangles */ function triBfHelp( int256 axis, int256[3][3][] memory trisBack, int256[3][3][] memory trisFront, int256 rot ) internal view returns (int256[3][3][] memory, int256[3][3][] memory) { int256[3][3][] memory trisBackNew = new int256[3][3][](trisBack.length); int256[3][3][] memory trisFrontNew = new int256[3][3][]( trisFront.length ); for (uint256 i = 0; i < trisBack.length; i++) { trisBackNew[i] = triRotHelp(axis, trisBack[i], rot); trisFrontNew[i] = triRotHelp(axis, trisFront[i], rot); } return (trisBackNew, trisFrontNew); } /** @dev get the maximum extent of the geometry (vertical or horizontal) */ function getExtents(int256[3][3][] memory tris) internal view returns (int256[3][2] memory) { int256 minX = MAX_INT; int256 maxX = MIN_INT; int256 minY = MAX_INT; int256 maxY = MIN_INT; int256 minZ = MAX_INT; int256 maxZ = MIN_INT; for (uint256 i = 0; i < tris.length; i++) { for (uint256 j = 0; j < tris[i].length; j++) { minX = ShackledMath.min(minX, tris[i][j][0]); maxX = ShackledMath.max(maxX, tris[i][j][0]); minY = ShackledMath.min(minY, tris[i][j][1]); maxY = ShackledMath.max(maxY, tris[i][j][1]); minZ = ShackledMath.min(minZ, tris[i][j][2]); maxZ = ShackledMath.max(maxZ, tris[i][j][2]); } } return [[minX, minY, minZ], [maxX, maxY, maxZ]]; } /** @dev go through each triangle and apply a 'height' */ function calculateZ( int256[3][3] memory tri, bytes32 tokenHash, uint256 nextTriIdx, GeomSpec memory geomSpec, bool front ) internal view returns (int256) { int256 h; string memory seedMod = string(abi.encodePacked("calcZ", nextTriIdx)); if (front) { if (geomSpec.id == 6) { h = 1; } else { if (randN(tokenHash, seedMod, 0, 10) > 9) { if (randN(tokenHash, seedMod, 0, 10) > 3) { h = 10; } else { h = 22; } } else { if (randN(tokenHash, seedMod, 0, 10) > 5) { h = 8; } else { h = 1; } } } } else { if (geomSpec.id == 6) { h = -1; } else { if (geomSpec.id == 5) { h = -randN(tokenHash, seedMod, 2, 20); } else { h = -2; } } } if (geomSpec.id == 5) { h += 10; } return h * geomSpec.depthMultiplier; } /** @dev roll a specId given a list of weightings */ function getSpecId(bytes32 tokenHash, int256[2][7] memory weightings) internal view returns (uint256) { int256 n = GeomUtils.randN( tokenHash, "specId", weightings[0][0], weightings[weightings.length - 1][1] ); for (uint256 i = 0; i < weightings.length; i++) { if (weightings[i][0] <= n && n <= weightings[i][1]) { return i; } } } /** @dev get a random number between two numbers with a uniform probability distribution @param randomSeed a hash that we can use to 'randomly' get a number @param seedModifier some string to make the result unique for this tokenHash @param min the minimum number (inclusive) @param max the maximum number (inclusive) examples: to get binary output (0 or 1), set min as 0 and max as 1 */ function randN( bytes32 randomSeed, string memory seedModifier, int256 min, int256 max ) internal view returns (int256) { /// use max() to ensure modulo != 0 return int256( uint256(keccak256(abi.encodePacked(randomSeed, seedModifier))) % uint256(ShackledMath.max(1, (max + 1 - min))) ) + min; } /** @dev clip an array of tris to a certain length (to trim empty tail slots) */ function clipTrisToLength(int256[3][3][] memory arr, uint256 desiredLen) internal view returns (int256[3][3][] memory) { uint256 n = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), n)) } return arr; } /** @dev clip an array of Z values to a certain length (to trim empty tail slots) */ function clipZsToLength(int256[] memory arr, uint256 desiredLen) internal view returns (int256[] memory) { uint256 n = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), n)) } return arr; } /** @dev make a copy of a triangle */ function copyTri(int256[3][3] memory tri) internal view returns (int256[3][3] memory) { return [ [tri[0][0], tri[0][1], tri[0][2]], [tri[1][0], tri[1][1], tri[1][2]], [tri[2][0], tri[2][1], tri[2][2]] ]; } /** @dev make a copy of an array of triangles */ function copyTris(int256[3][3][] memory tris) internal view returns (int256[3][3][] memory) { int256[3][3][] memory newTris = new int256[3][3][](tris.length); for (uint256 i = 0; i < tris.length; i++) { newTris[i] = copyTri(tris[i]); } return newTris; } } // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library ShackledStructs { struct Metadata { string colorScheme; /// name of the color scheme string geomSpec; /// name of the geometry specification uint256 nPrisms; /// number of prisms made string pseudoSymmetry; /// horizontal, vertical, diagonal string wireframe; /// enabled or disabled string inversion; /// enabled or disabled } struct RenderParams { uint256[3][] faces; /// index of verts and colorss used for each face (triangle) int256[3][] verts; /// x, y, z coordinates used in the geometry int256[3][] cols; /// colors of each vert int256[3] objPosition; /// position to place the object int256 objScale; /// scalar for the object int256[3][2] backgroundColor; /// color of the background (gradient) LightingParams lightingParams; /// parameters for the lighting bool perspCamera; /// true = perspective camera, false = orthographic bool backfaceCulling; /// whether to implement backface culling (saves gas!) bool invert; /// whether to invert colors in the final encoding stage bool wireframe; /// whether to only render edges } /// struct for testing lighting struct LightingParams { bool applyLighting; /// true = apply lighting, false = don't apply lighting int256 lightAmbiPower; /// power of the ambient light int256 lightDiffPower; /// power of the diffuse light int256 lightSpecPower; /// power of the specular light uint256 inverseShininess; /// shininess of the material int256[3] lightPos; /// position of the light int256[3] lightColSpec; /// color of the specular light int256[3] lightColDiff; /// color of the diffuse light int256[3] lightColAmbi; /// color of the ambient light } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library ShackledMath { /** @dev Get the minimum of two numbers */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** @dev Get the maximum of two numbers */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** @dev perform a modulo operation, with support for negative numbers */ function mod(int256 n, int256 m) internal pure returns (int256) { if (n < 0) { return ((n % m) + m) % m; } else { return n % m; } } /** @dev 'randomly' select n numbers between 0 and m (useful for getting a randomly sampled index) */ function randomIdx( bytes32 seedModifier, uint256 n, // number of elements to select uint256 m // max value of elements ) internal pure returns (uint256[] memory) { uint256[] memory result = new uint256[](n); for (uint256 i = 0; i < n; i++) { result[i] = uint256(keccak256(abi.encodePacked(seedModifier, i))) % m; } return result; } /** @dev create a 2d array and fill with a single value */ function get2dArray( uint256 m, uint256 q, int256 value ) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; } /** @dev get the absolute of a number */ function abs(int256 x) internal pure returns (int256) { assembly { if slt(x, 0) { x := sub(0, x) } } return x; } /** @dev get the square root of a number */ function sqrt(int256 y) internal pure returns (int256 z) { assembly { if sgt(y, 3) { z := y let x := add(div(y, 2), 1) for { } slt(x, z) { } { z := x x := div(add(div(y, x), x), 2) } } if and(slt(y, 4), sgt(y, 0)) { z := 1 } } } /** @dev get the hypotenuse of a triangle given the length of 2 sides */ function hypot(int256 x, int256 y) internal pure returns (int256) { int256 sumsq; assembly { let xsq := mul(x, x) let ysq := mul(y, y) sumsq := add(xsq, ysq) } return sqrt(sumsq); } /** @dev addition between two vectors (size 3) */ function vector3Add(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, add(mload(v1), mload(v2))) mstore( add(result, 0x20), add(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), add(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev subtraction between two vectors (size 3) */ function vector3Sub(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, sub(mload(v1), mload(v2))) mstore( add(result, 0x20), sub(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), sub(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev multiply a vector (size 3) by a constant */ function vector3MulScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, mul(mload(v), a)) mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a)) } } /** @dev divide a vector (size 3) by a constant */ function vector3DivScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, sdiv(mload(v), a)) mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a)) } } /** @dev get the length of a vector (size 3) */ function vector3Len(int256[3] memory v) internal pure returns (int256) { int256 res; assembly { let x := mload(v) let y := mload(add(v, 0x20)) let z := mload(add(v, 0x40)) res := add(add(mul(x, x), mul(y, y)), mul(z, z)) } return sqrt(res); } /** @dev scale and then normalise a vector (size 3) */ function vector3NormX(int256[3] memory v, int256 fidelity) internal pure returns (int256[3] memory result) { int256 l = vector3Len(v); assembly { mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l)) mstore( add(result, 0x20), sdiv(mul(fidelity, mload(add(v, 0x20))), l) ) mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l)) } } /** @dev get the dot-product of two vectors (size 3) */ function vector3Dot(int256[3] memory v1, int256[3] memory v2) internal view returns (int256 result) { assembly { result := add( add( mul(mload(v1), mload(v2)), mul(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ), mul(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev get the cross product of two vectors (size 3) */ function crossProduct(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore( result, sub( mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))), mul(mload(add(v1, 0x40)), mload(add(v2, 0x20))) ) ) mstore( add(result, 0x20), sub( mul(mload(add(v1, 0x40)), mload(v2)), mul(mload(v1), mload(add(v2, 0x40))) ) ) mstore( add(result, 0x40), sub( mul(mload(v1), mload(add(v2, 0x20))), mul(mload(add(v1, 0x20)), mload(v2)) ) ) } } /** @dev linearly interpolate between two vectors (size 12) */ function vector12Lerp( int256[12] memory v1, int256[12] memory v2, int256 ir, int256 scaleFactor ) internal view returns (int256[12] memory result) { int256[12] memory vd = vector12Sub(v2, v1); // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), add( // v1[i] + (ir * vd[i]) / 1e3 mload(add(v1, ix)), sdiv(mul(ir, mload(add(vd, ix))), 1000) ) ) } } } /** @dev subtraction between two vectors (size 12) */ function vector12Sub(int256[12] memory v1, int256[12] memory v2) internal view returns (int256[12] memory result) { // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), sub( // v1[ix] - v2[ix] mload(add(v1, ix)), mload(add(v2, ix)) ) ) } } } /** @dev map a number from one range into another */ function mapRangeToRange( int256 num, int256 inMin, int256 inMax, int256 outMin, int256 outMax ) internal pure returns (int256 res) { assembly { res := add( sdiv( mul(sub(outMax, outMin), sub(num, inMin)), sub(inMax, inMin) ), outMin ) } } } // SPDX-License-Identifier: MIT /** * @notice Solidity library offering basic trigonometry functions where inputs and outputs are * integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18. * * This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas * which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol * * Compared to Lefteris' implementation, this version makes the following changes: * - Uses a 32 bits instead of 16 bits for improved accuracy * - Updated for Solidity 0.8.x * - Various gas optimizations * - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the * integer format used by the algorithm * * Lefertis' implementation is based off Dave Dribin's trigint C library * http://www.dribin.org/dave/trigint/ * * Which in turn is based from a now deleted article which can be found in the Wayback Machine: * http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html */ pragma solidity ^0.8.0; library Trigonometry { // Table index into the trigonometric table uint256 constant INDEX_WIDTH = 8; // Interpolation between successive entries in the table uint256 constant INTERP_WIDTH = 16; uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH; uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH; uint32 constant ANGLES_IN_CYCLE = 1073741824; uint32 constant QUADRANT_HIGH_MASK = 536870912; uint32 constant QUADRANT_LOW_MASK = 268435456; uint256 constant SINE_TABLE_SIZE = 256; // Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for // interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ uint256 constant PI = 3141592653589793238; uint256 constant TWO_PI = 2 * PI; uint256 constant PI_OVER_TWO = PI / 2; // The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant // bytes array because constant arrays are not supported in Solidity. Each entry in the lookup // table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size // of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of // 256 defined above) uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes uint256 constant entry_mask = ((1 << (8 * entry_bytes)) - 1); // mask used to cast bytes32 -> lookup table entry bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff"; /** * @notice Return the sine of a value, specified in radians scaled by 1e18 * @dev This algorithm for converting sine only uses integer values, and it works by dividing the * circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the * standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to * 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard * range of -1 to 1, again scaled by 1e18 * @param _angle Angle to convert * @return Result scaled by 1e18 */ function sin(uint256 _angle) internal pure returns (int256) { unchecked { // Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range // of 0 to 1,073,741,824 _angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI; // Apply a mask on an integer to extract a certain number of bits, where angle is the integer // whose bits we want to get, the width is the width of the bits (in bits) we want to extract, // and the offset is the offset of the bits (in bits) we want to extract. The result is an // integer containing _width bits of _value starting at the offset bit uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1); uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1); // The lookup table only contains data for one quadrant (since sin is symmetric around both // axes), so here we figure out which quadrant we're in, then we lookup the values in the // table then modify values accordingly bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0; bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0; if (!is_odd_quadrant) { index = SINE_TABLE_SIZE - 1 - index; } bytes memory table = sin_table; // We are looking for two consecutive indices in our lookup table // Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n` // therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2` uint256 offset1_2 = (index + 2) * entry_bytes; // This following snippet will function for any entry_bytes <= 15 uint256 x1_2; assembly { // mload will grab one word worth of bytes (32), as that is the minimum size in EVM x1_2 := mload(add(table, offset1_2)) } // We now read the last two numbers of size entry_bytes from x1_2 // in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh // therefore: entry_mask = 0xFFFFFFFF // 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678 // 0x00...12345678 & 0xFFFFFFFF = 0x12345678 uint256 x1 = (x1_2 >> (8 * entry_bytes)) & entry_mask; // 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh uint256 x2 = x1_2 & entry_mask; // Approximate angle by interpolating in the table, accounting for the quadrant uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH; int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation); if (is_negative_quadrant) { sine *= -1; } // Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18. // This can never overflow because sine is bounded by the above values return (sine * 1e18) / 2_147_483_647; } } /** * @notice Return the cosine of a value, specified in radians scaled by 1e18 * @dev This is identical to the sin() method, and just computes the value by delegating to the * sin() method using the identity cos(x) = sin(x + pi/2) * @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate * @param _angle Angle to convert * @return Result scaled by 1e18 */ function cos(uint256 _angle) internal pure returns (int256) { unchecked { return sin(_angle + PI_OVER_TWO); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledGenesis.sol"; contract XShackledGenesis { constructor() {} function xgenerateGenesisPiece(bytes32 tokenHash) external view returns (ShackledStructs.RenderParams memory, ShackledStructs.Metadata memory) { return ShackledGenesis.generateGenesisPiece(tokenHash); } function xgenerateGeometryAndColors(bytes32 tokenHash,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory, ColorUtils.ColScheme memory, GeomUtils.GeomSpec memory, GeomUtils.GeomVars memory) { return ShackledGenesis.generateGeometryAndColors(tokenHash,objPosition); } function xcreate2dTris(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec) external view returns (int256[3][3][] memory, int256[] memory, int256[] memory) { return ShackledGenesis.create2dTris(tokenHash,geomSpec); } function xprismify(bytes32 tokenHash,int256[3][3][] calldata tris,int256[] calldata zFronts,int256[] calldata zBacks) external view returns (GeomUtils.GeomVars memory) { return ShackledGenesis.prismify(tokenHash,tris,zFronts,zBacks); } function xmakeFacesVertsCols(bytes32 tokenHash,int256[3][3][] calldata tris,GeomUtils.GeomVars calldata geomVars,ColorUtils.ColScheme calldata scheme,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory) { return ShackledGenesis.makeFacesVertsCols(tokenHash,tris,geomVars,scheme,objPosition); } } contract XColorUtils { constructor() {} function xgetColForPrism(bytes32 tokenHash,int256[3][3] calldata triFront,ColorUtils.SubScheme calldata subScheme,int256[3][2] calldata extents) external view returns (int256[3][6] memory) { return ColorUtils.getColForPrism(tokenHash,triFront,subScheme,extents); } function xgetSchemeId(bytes32 tokenHash,int256[2][10] calldata weightings) external view returns (uint256) { return ColorUtils.getSchemeId(tokenHash,weightings); } function xcopyColor(int256[3] calldata c) external view returns (int256[3] memory) { return ColorUtils.copyColor(c); } function xgetScheme(bytes32 tokenHash,int256[3][3][] calldata tris) external view returns (ColorUtils.ColScheme memory) { return ColorUtils.getScheme(tokenHash,tris); } function xhsv2rgb(int256 h,int256 s,int256 v) external view returns (int256[3] memory) { return ColorUtils.hsv2rgb(h,s,v); } function xrgb2hsv(int256 r,int256 g,int256 b) external view returns (int256[3] memory) { return ColorUtils.rgb2hsv(r,g,b); } function xgetJiggle(int256[3] calldata jiggle,bytes32 randomSeed,int256 seedModifier) external view returns (int256[3] memory) { return ColorUtils.getJiggle(jiggle,randomSeed,seedModifier); } function xinArray(uint256[] calldata array,uint256 value) external view returns (bool) { return ColorUtils.inArray(array,value); } function xapplyDirHelp(int256[3][3] calldata triFront,int256[3] calldata colA,int256[3] calldata colB,int256 dirCode,bool isInnerGradient,int256[3][2] calldata extents) external view returns (int256[3][3] memory) { return ColorUtils.applyDirHelp(triFront,colA,colB,dirCode,isInnerGradient,extents); } function xgetOrderedPointIdxsInDir(int256[3][3] calldata tri,int256 dirCode) external view returns (uint256[3] memory) { return ColorUtils.getOrderedPointIdxsInDir(tri,dirCode); } function xinterpColHelp(int256[3] calldata colA,int256[3] calldata colB,int256 low,int256 high,int256 val) external view returns (int256[3] memory) { return ColorUtils.interpColHelp(colA,colB,low,high,val); } function xgetHighlightPrismIdxs(int256[3][3][] calldata tris,bytes32 tokenHash,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) { return ColorUtils.getHighlightPrismIdxs(tris,tokenHash,nHighlights,varCode,selCode); } function xgetSortedTrisIdxs(int256[3][3][] calldata tris,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) { return ColorUtils.getSortedTrisIdxs(tris,nHighlights,varCode,selCode); } } contract XGeomUtils { constructor() {} function xgenerateSpec(bytes32 tokenHash) external view returns (GeomUtils.GeomSpec memory) { return GeomUtils.generateSpec(tokenHash); } function xmakeAdjacentTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) { return GeomUtils.makeAdjacentTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth); } function xmakeVerticallyOppositeTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) { return GeomUtils.makeVerticallyOppositeTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth); } function xmakeTriVertOpp(int256[3][3] calldata refTri,GeomUtils.GeomSpec calldata geomSpec,int256 sideIdx,int256 scale) external view returns (int256[3][3] memory) { return GeomUtils.makeTriVertOpp(refTri,geomSpec,sideIdx,scale); } function xmakeTriAdjacent(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec,uint256 attemptNum,int256[3][3] calldata refTri,int256 sideIdx,int256 scale,int256 depth) external view returns (int256[3][3] memory) { return GeomUtils.makeTriAdjacent(tokenHash,geomSpec,attemptNum,refTri,sideIdx,scale,depth); } function xmakeTri(int256[3] calldata centre,int256 radius,int256 angle) external view returns (int256[3][3] memory) { return GeomUtils.makeTri(centre,radius,angle); } function xvector3RotateX(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateX(v,deg); } function xvector3RotateY(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateY(v,deg); } function xvector3RotateZ(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateZ(v,deg); } function xtrigHelper(int256 deg) external view returns (int256, int256) { return GeomUtils.trigHelper(deg); } function xgetCenterVec(int256[3][3] calldata tri) external view returns (int256[3] memory) { return GeomUtils.getCenterVec(tri); } function xgetRadiusLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getRadiusLen(tri); } function xgetSideLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getSideLen(tri); } function xgetPerpLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getPerpLen(tri); } function xisTriPointingUp(int256[3][3] calldata tri) external view returns (bool) { return GeomUtils.isTriPointingUp(tri); } function xareTrisClose(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) { return GeomUtils.areTrisClose(tri1,tri2); } function xareTrisPointsOverlapping(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) { return GeomUtils.areTrisPointsOverlapping(tri1,tri2); } function xisPointInTri(int256[3][3] calldata tri,int256[3] calldata p) external view returns (bool) { return GeomUtils.isPointInTri(tri,p); } function xisTriOverlappingWithTris(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) { return GeomUtils.isTriOverlappingWithTris(tri,tris,nextTriIdx); } function xisPointCloseToLine(int256[3] calldata p,int256[3] calldata l1,int256[3] calldata l2) external view returns (bool) { return GeomUtils.isPointCloseToLine(p,l1,l2); } function xisTrisPointsCloseToLines(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) { return GeomUtils.isTrisPointsCloseToLines(tri,tris,nextTriIdx); } function xisTriLegal(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx,int256 minTriRad) external view returns (bool) { return GeomUtils.isTriLegal(tri,tris,nextTriIdx,minTriRad); } function xattemptToAddTri(int256[3][3] calldata tri,bytes32 tokenHash,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec) external view returns (bool) { return GeomUtils.attemptToAddTri(tri,tokenHash,triVars,geomSpec); } function xtriRotHelp(int256 axis,int256[3][3] calldata tri,int256 rot) external view returns (int256[3][3] memory) { return GeomUtils.triRotHelp(axis,tri,rot); } function xtriBfHelp(int256 axis,int256[3][3][] calldata trisBack,int256[3][3][] calldata trisFront,int256 rot) external view returns (int256[3][3][] memory, int256[3][3][] memory) { return GeomUtils.triBfHelp(axis,trisBack,trisFront,rot); } function xgetExtents(int256[3][3][] calldata tris) external view returns (int256[3][2] memory) { return GeomUtils.getExtents(tris); } function xcalculateZ(int256[3][3] calldata tri,bytes32 tokenHash,uint256 nextTriIdx,GeomUtils.GeomSpec calldata geomSpec,bool front) external view returns (int256) { return GeomUtils.calculateZ(tri,tokenHash,nextTriIdx,geomSpec,front); } function xgetSpecId(bytes32 tokenHash,int256[2][7] calldata weightings) external view returns (uint256) { return GeomUtils.getSpecId(tokenHash,weightings); } function xrandN(bytes32 randomSeed,string calldata seedModifier,int256 min,int256 max) external view returns (int256) { return GeomUtils.randN(randomSeed,seedModifier,min,max); } function xclipTrisToLength(int256[3][3][] calldata arr,uint256 desiredLen) external view returns (int256[3][3][] memory) { return GeomUtils.clipTrisToLength(arr,desiredLen); } function xclipZsToLength(int256[] calldata arr,uint256 desiredLen) external view returns (int256[] memory) { return GeomUtils.clipZsToLength(arr,desiredLen); } function xcopyTri(int256[3][3] calldata tri) external view returns (int256[3][3] memory) { return GeomUtils.copyTri(tri); } function xcopyTris(int256[3][3][] calldata tris) external view returns (int256[3][3][] memory) { return GeomUtils.copyTris(tris); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledMath.sol"; contract XShackledMath { constructor() {} function xmin(int256 a,int256 b) external pure returns (int256) { return ShackledMath.min(a,b); } function xmax(int256 a,int256 b) external pure returns (int256) { return ShackledMath.max(a,b); } function xmod(int256 n,int256 m) external pure returns (int256) { return ShackledMath.mod(n,m); } function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) { return ShackledMath.randomIdx(seedModifier,n,m); } function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) { return ShackledMath.get2dArray(m,q,value); } function xabs(int256 x) external pure returns (int256) { return ShackledMath.abs(x); } function xsqrt(int256 y) external pure returns (int256) { return ShackledMath.sqrt(y); } function xhypot(int256 x,int256 y) external pure returns (int256) { return ShackledMath.hypot(x,y); } function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Add(v1,v2); } function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Sub(v1,v2); } function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3MulScalar(v,a); } function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3DivScalar(v,a); } function xvector3Len(int256[3] calldata v) external pure returns (int256) { return ShackledMath.vector3Len(v); } function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) { return ShackledMath.vector3NormX(v,fidelity); } function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) { return ShackledMath.vector3Dot(v1,v2); } function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.crossProduct(v1,v2); } function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) { return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor); } function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) { return ShackledMath.vector12Sub(v1,v2); } function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) { return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledStructs.sol"; contract XShackledStructs { constructor() {} } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/Trigonometry.sol"; contract XTrigonometry { constructor() {} function xsin(uint256 _angle) external pure returns (int256) { return Trigonometry.sin(_angle); } function xcos(uint256 _angle) external pure returns (int256) { return Trigonometry.cos(_angle); } }
* @dev get the maximum extent of the geometry (vertical or horizontal) */
function getExtents(int256[3][3][] memory tris) internal view returns (int256[3][2] memory) { int256 minX = MAX_INT; int256 maxX = MIN_INT; int256 minY = MAX_INT; int256 maxY = MIN_INT; int256 minZ = MAX_INT; int256 maxZ = MIN_INT; for (uint256 i = 0; i < tris.length; i++) { for (uint256 j = 0; j < tris[i].length; j++) { minX = ShackledMath.min(minX, tris[i][j][0]); maxX = ShackledMath.max(maxX, tris[i][j][0]); minY = ShackledMath.min(minY, tris[i][j][1]); maxY = ShackledMath.max(maxY, tris[i][j][1]); minZ = ShackledMath.min(minZ, tris[i][j][2]); maxZ = ShackledMath.max(maxZ, tris[i][j][2]); } } return [[minX, minY, minZ], [maxX, maxY, maxZ]]; }
1,257,294
[ 1, 588, 326, 4207, 11933, 434, 326, 5316, 261, 17824, 578, 10300, 13, 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 ]
[ 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, 336, 2482, 4877, 12, 474, 5034, 63, 23, 6362, 23, 6362, 65, 3778, 433, 291, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 474, 5034, 63, 23, 6362, 22, 65, 3778, 13, 203, 565, 288, 203, 3639, 509, 5034, 21586, 273, 4552, 67, 3217, 31, 203, 3639, 509, 5034, 21482, 273, 6989, 67, 3217, 31, 203, 3639, 509, 5034, 21355, 273, 4552, 67, 3217, 31, 203, 3639, 509, 5034, 21509, 273, 6989, 67, 3217, 31, 203, 3639, 509, 5034, 1131, 62, 273, 4552, 67, 3217, 31, 203, 3639, 509, 5034, 943, 62, 273, 6989, 67, 3217, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 433, 291, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 433, 291, 63, 77, 8009, 2469, 31, 525, 27245, 288, 203, 7734, 21586, 273, 2638, 484, 1259, 10477, 18, 1154, 12, 1154, 60, 16, 433, 291, 63, 77, 6362, 78, 6362, 20, 19226, 203, 7734, 21482, 273, 2638, 484, 1259, 10477, 18, 1896, 12, 1896, 60, 16, 433, 291, 63, 77, 6362, 78, 6362, 20, 19226, 203, 7734, 21355, 273, 2638, 484, 1259, 10477, 18, 1154, 12, 1154, 61, 16, 433, 291, 63, 77, 6362, 78, 6362, 21, 19226, 203, 7734, 21509, 273, 2638, 484, 1259, 10477, 18, 1896, 12, 1896, 61, 16, 433, 291, 63, 77, 6362, 78, 6362, 21, 19226, 203, 7734, 1131, 62, 273, 2638, 484, 1259, 10477, 18, 1154, 12, 1154, 62, 16, 433, 291, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } abstract contract Ownable is Context { address payable private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address payable msgSender = payable(_msgSender()); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address payable) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IDEXV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IDEXV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IDEXV2Router01 { 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 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); } interface IDEXV2Router02 is IDEXV2Router01 { 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; } contract CZIX is Ownable { IDEXV2Router02 public Router; address public Pair; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public accountLimit; uint256 public singleTransferLimit; uint256 public swapCooldownDuration; struct AccountStatus { bool feeExcluded; bool accountLimitExcluded; bool transferLimitExcluded; bool blacklistedBot; uint256 swapCooldown; } mapping(address => AccountStatus) public statuses; mapping(address => uint256) public balanceOf; mapping(address => uint256) public freezeOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event Freeze(address indexed from, uint256 value); event Unfreeze(address indexed from, uint256 value); event FeeExclusion(address indexed account, bool isExcluded); event AccountLimitExclusion(address indexed account, bool isExcluded); event TransferLimitExclusion(address indexed account, bool isExcluded); constructor( uint256 initialSupply, string memory tokenName, uint8 decimalUnits, string memory tokenSymbol, address _router ) { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes totalSupply = initialSupply * 10**decimals; // Update total supply // Set router and create swap pair _setRouterAddress(_router); // Exclude the owner and this contract from transfer restrictions statuses[owner()] = AccountStatus(true, true, true, false, 0); statuses[address(this)] = AccountStatus(true, true, true, false, 0); // Exclude swap pair and swap router from account limit statuses[Pair].accountLimitExcluded = true; statuses[address(Router)].accountLimitExcluded = true; // Set initial settings accountLimit = SafeMath.div(totalSupply, 100); singleTransferLimit = SafeMath.div(totalSupply, 1000); swapCooldownDuration = 1 minutes; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /* Send coins */ function transfer(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(amount > 0); require(balanceOf[msg.sender] >= amount); // Check if the sender has enough require(balanceOf[recipient] + amount >= balanceOf[recipient]); // Check for overflows _checkBotBlacklisting(msg.sender, recipient); _checkTransferLimit(msg.sender, recipient, amount); _checkAccountLimit(recipient, amount, balanceOf[recipient]); _checkSwapCooldown(msg.sender, recipient); balanceOf[msg.sender] = SafeMath.sub(balanceOf[msg.sender], amount); // Subtract from the sender balanceOf[recipient] = SafeMath.add(balanceOf[recipient], amount); // Add the same to the recipient emit Transfer(msg.sender, recipient, amount); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 amount) public returns (bool success) { require(amount > 0); allowance[msg.sender][_spender] = amount; return true; } /* A contract attempts to get the coins */ function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool success) { require(recipient != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(amount > 0); require(balanceOf[sender] >= amount); // Check if the sender has enough require(balanceOf[recipient] + amount >= balanceOf[recipient]); // Check for overflows require(amount <= allowance[sender][msg.sender]); // Check allowance _checkBotBlacklisting(sender, recipient); _checkTransferLimit(sender, recipient, amount); _checkAccountLimit(recipient, amount, balanceOf[recipient]); _checkSwapCooldown(sender, recipient); balanceOf[sender] = SafeMath.sub(balanceOf[sender], amount); // Subtract from the sender balanceOf[recipient] = SafeMath.add(balanceOf[recipient], amount); // Add the same to the recipient allowance[sender][msg.sender] = SafeMath.sub( allowance[sender][msg.sender], amount ); emit Transfer(sender, recipient, amount); return true; } function burn(uint256 amount) public returns (bool success) { require(balanceOf[msg.sender] >= amount); // Check if the sender has enough require(amount > 0); balanceOf[msg.sender] = SafeMath.sub(balanceOf[msg.sender], amount); // Subtract from the sender totalSupply = SafeMath.sub(totalSupply, amount); // Updates totalSupply emit Burn(msg.sender, amount); return true; } function freeze(uint256 amount) public returns (bool success) { require(balanceOf[msg.sender] >= amount); // Check if the sender has enough require(amount > 0); balanceOf[msg.sender] = SafeMath.sub(balanceOf[msg.sender], amount); // Subtract from the sender freezeOf[msg.sender] = SafeMath.add(freezeOf[msg.sender], amount); // Updates totalSupply emit Freeze(msg.sender, amount); return true; } function unfreeze(uint256 amount) public returns (bool success) { require(freezeOf[msg.sender] >= amount); // Check if the sender has enough require(amount > 0); freezeOf[msg.sender] = SafeMath.sub(freezeOf[msg.sender], amount); // Subtract from the sender balanceOf[msg.sender] = SafeMath.add(balanceOf[msg.sender], amount); emit Unfreeze(msg.sender, amount); return true; } function setFeeExclusion(address account, bool isExcluded) public onlyOwner { statuses[account].feeExcluded = isExcluded; emit FeeExclusion(account, isExcluded); } function setAccountLimitExclusion(address account, bool isExcluded) public onlyOwner { statuses[account].accountLimitExcluded = isExcluded; emit AccountLimitExclusion(account, isExcluded); } function setTransferLimitExclusion(address account, bool isExcluded) public onlyOwner { statuses[account].transferLimitExcluded = isExcluded; emit TransferLimitExclusion(account, isExcluded); } function setBotsBlacklisting(address[] memory bots, bool isBlacklisted) public onlyOwner { for (uint256 i = 0; i < bots.length; i++) { statuses[bots[i]].blacklistedBot = isBlacklisted; } } function _checkBotBlacklisting(address sender, address recipient) internal view { require(!statuses[sender].blacklistedBot, "Sender is blacklisted"); require( !statuses[recipient].blacklistedBot, "Recipient is blacklisted" ); } function _checkTransferLimit( address sender, address recipient, uint256 amount ) internal view { if ( !statuses[sender].transferLimitExcluded && !statuses[recipient].transferLimitExcluded ) { require( amount <= singleTransferLimit, "Transfer amount exceeds the limit" ); } } function _checkAccountLimit( address recipient, uint256 amount, uint256 recipientBalance ) internal view { if (!statuses[recipient].accountLimitExcluded) { require( recipientBalance + amount <= accountLimit, "Recipient has reached account tokens limit" ); } } function _checkSwapCooldown(address sender, address recipient) internal { if ( swapCooldownDuration > 0 && sender == Pair && recipient != address(Router) ) { require( statuses[recipient].swapCooldown < block.timestamp, "Swap is cooling down" ); statuses[recipient].swapCooldown = block.timestamp + swapCooldownDuration; } } //set Router address function _setRouterAddress(address routerAddress_) internal { IDEXV2Router02 _Router = IDEXV2Router02(routerAddress_); Pair = IDEXV2Factory(_Router.factory()).createPair( address(this), _Router.WETH() ); Router = _Router; } // set router owner just incase function ChangeRouter(address _router) public onlyOwner { require(IDEXV2Router02(_router) != Router, "Already Set"); _setRouterAddress(_router); } function setAccountLimit(uint256 amount) public onlyOwner { accountLimit = amount; } function setSingleTransferLimit(uint256 amount) public onlyOwner { singleTransferLimit = amount; } function setSwapCooldownDuration(uint256 duration) public onlyOwner { swapCooldownDuration = duration; } // can accept ether receive() external payable {} // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner { owner().transfer(amount); } }
Updates totalSupply
totalSupply = SafeMath.sub(totalSupply, amount);
15,799,468
[ 1, 5121, 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, 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, 3639, 2078, 3088, 1283, 273, 14060, 10477, 18, 1717, 12, 4963, 3088, 1283, 16, 3844, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "./TokenBase/Base.sol"; /** * @title dForce's Lending Protocol Contract. * @notice iTokens which wrap an EIP-20 underlying. * @author dForce Team. */ contract iToken is Base { using SafeERC20Upgradeable for IERC20Upgradeable; /** * @notice Expects to call only once to initialize a new market. * @param _underlyingToken The underlying token address. * @param _name Token name. * @param _symbol Token symbol. * @param _controller Core controller contract address. * @param _interestRateModel Token interest rate model contract address. */ function initialize( address _underlyingToken, string memory _name, string memory _symbol, IControllerInterface _controller, IInterestRateModelInterface _interestRateModel ) external initializer { require( address(_underlyingToken) != address(0), "initialize: underlying address should not be zero address!" ); require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); require( address(_interestRateModel) != address(0), "initialize: interest model address should not be zero address!" ); _initialize( _name, _symbol, ERC20(_underlyingToken).decimals(), _controller, _interestRateModel ); underlying = IERC20Upgradeable(_underlyingToken); } /** * @notice In order to support deflationary token, returns the changed amount. * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom`. */ function _doTransferIn(address _sender, uint256 _amount) internal override returns (uint256) { uint256 _balanceBefore = underlying.balanceOf(address(this)); underlying.safeTransferFrom(_sender, address(this), _amount); return underlying.balanceOf(address(this)).sub(_balanceBefore); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer`. */ function _doTransferOut(address payable _recipient, uint256 _amount) internal override { underlying.safeTransfer(_recipient, _amount); } /** * @dev Gets balance of this contract in terms of the underlying */ function _getCurrentCash() internal view override returns (uint256) { return underlying.balanceOf(address(this)); } /** * @dev Caller deposits assets into the market and `_recipient` receives iToken in exchange. * @param _recipient The account that would receive the iToken. * @param _mintAmount The amount of the underlying token to deposit. */ function mint(address _recipient, uint256 _mintAmount) external nonReentrant settleInterest { _mintInternal(_recipient, _mintAmount); } /** * @dev Caller redeems specified iToken from `_from` to get underlying token. * @param _from The account that would burn the iToken. * @param _redeemiToken The number of iToken to redeem. */ function redeem(address _from, uint256 _redeemiToken) external nonReentrant settleInterest { _redeemInternal( _from, _redeemiToken, _redeemiToken.rmul(_exchangeRateInternal()) ); } /** * @dev Caller redeems specified underlying from `_from` to get underlying token. * @param _from The account that would burn the iToken. * @param _redeemUnderlying The number of underlying to redeem. */ function redeemUnderlying(address _from, uint256 _redeemUnderlying) external nonReentrant settleInterest { _redeemInternal( _from, _redeemUnderlying.rdivup(_exchangeRateInternal()), _redeemUnderlying ); } /** * @dev Caller borrows tokens from the protocol to their own address. * @param _borrowAmount The amount of the underlying token to borrow. */ function borrow(uint256 _borrowAmount) external nonReentrant settleInterest { _borrowInternal(msg.sender, _borrowAmount); } /** * @dev Caller repays their own borrow. * @param _repayAmount The amount to repay. */ function repayBorrow(uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, msg.sender, _repayAmount); } /** * @dev Caller repays a borrow belonging to borrower. * @param _borrower the account with the debt being payed off. * @param _repayAmount The amount to repay. */ function repayBorrowBehalf(address _borrower, uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, _borrower, _repayAmount); } /** * @dev The caller liquidates the borrowers collateral. * @param _borrower The account whose borrow should be liquidated. * @param _assetCollateral The market in which to seize collateral from the borrower. * @param _repayAmount The amount to repay. */ function liquidateBorrow( address _borrower, uint256 _repayAmount, address _assetCollateral ) external nonReentrant settleInterest { _liquidateBorrowInternal(_borrower, _repayAmount, _assetCollateral); } /** * @dev Transfers this tokens to the liquidator. * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iTokens to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external override nonReentrant { _seizeInternal(msg.sender, _liquidator, _borrower, _seizeTokens); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function updateInterest() external override returns (bool) { _updateInterest(); return true; } /** * @dev Gets the newest exchange rate by accruing interest. */ function exchangeRateCurrent() external returns (uint256) { // Accrues interest. _updateInterest(); return _exchangeRateInternal(); } /** * @dev Calculates the exchange rate without accruing interest. */ function exchangeRateStored() external view override returns (uint256) { return _exchangeRateInternal(); } /** * @dev Gets the underlying balance of the `_account`. * @param _account The address of the account to query. */ function balanceOfUnderlying(address _account) external returns (uint256) { // Accrues interest. _updateInterest(); return _exchangeRateInternal().rmul(balanceOf[_account]); } /** * @dev Gets the user's borrow balance with the latest `borrowIndex`. */ function borrowBalanceCurrent(address _account) external nonReentrant returns (uint256) { // Accrues interest. _updateInterest(); return _borrowBalanceInternal(_account); } /** * @dev Gets the borrow balance of user without accruing interest. */ function borrowBalanceStored(address _account) external view override returns (uint256) { return _borrowBalanceInternal(_account); } /** * @dev Gets user borrowing information. */ function borrowSnapshot(address _account) external view returns (uint256, uint256) { return ( accountBorrows[_account].principal, accountBorrows[_account].interestIndex ); } /** * @dev Gets the current total borrows by accruing interest. */ function totalBorrowsCurrent() external returns (uint256) { // Accrues interest. _updateInterest(); return totalBorrows; } /** * @dev Returns the current per-block borrow interest rate. */ function borrowRatePerBlock() public view returns (uint256) { return interestRateModel.getBorrowRate( _getCurrentCash(), totalBorrows, totalReserves ); } /** * @dev Returns the current per-block supply interest rate. * Calculates the supply rate: * underlying = totalSupply × exchangeRate * borrowsPer = totalBorrows ÷ underlying * supplyRate = borrowRate × (1-reserveFactor) × borrowsPer */ function supplyRatePerBlock() external view returns (uint256) { // `_underlyingScaled` is scaled by 1e36. uint256 _underlyingScaled = totalSupply.mul(_exchangeRateInternal()); if (_underlyingScaled == 0) return 0; uint256 _totalBorrowsScaled = totalBorrows.mul(BASE); return borrowRatePerBlock().tmul( BASE.sub(reserveRatio), _totalBorrowsScaled.rdiv(_underlyingScaled) ); } /** * @dev Get cash balance of this iToken in the underlying token. */ function getCash() external view returns (uint256) { return _getCurrentCash(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interface/IFlashloanExecutor.sol"; import "../library/SafeRatioMath.sol"; import "./TokenERC20.sol"; /** * @title dForce's lending Base Contract * @author dForce */ abstract contract Base is TokenERC20 { using SafeRatioMath for uint256; /** * @notice Expects to call only once to create a new lending market. * @param _name Token name. * @param _symbol Token symbol. * @param _controller Core controller contract address. * @param _interestRateModel Token interest rate model contract address. */ function _initialize( string memory _name, string memory _symbol, uint8 _decimals, IControllerInterface _controller, IInterestRateModelInterface _interestRateModel ) internal virtual { controller = _controller; interestRateModel = _interestRateModel; accrualBlockNumber = block.number; borrowIndex = BASE; flashloanFeeRatio = 0.0008e18; protocolFeeRatio = 0.25e18; __Ownable_init(); __ERC20_init(_name, _symbol, _decimals); __ReentrancyGuard_init(); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(_name)), keccak256(bytes("1")), _getChainId(), address(this) ) ); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Check whether is a iToken contract, return false for iMSD contract. */ function isiToken() external pure virtual returns (bool) { return true; } //---------------------------------- //******** Main calculation ******** //---------------------------------- struct InterestLocalVars { uint256 borrowRate; uint256 currentBlockNumber; uint256 currentCash; uint256 totalBorrows; uint256 totalReserves; uint256 borrowIndex; uint256 blockDelta; uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 newTotalBorrows; uint256 newTotalReserves; uint256 newBorrowIndex; } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function _updateInterest() internal virtual override { // When more calls in the same block, only the first one takes effect, so for the // following calls, nothing updates. if (block.number != accrualBlockNumber) { InterestLocalVars memory _vars; _vars.currentCash = _getCurrentCash(); _vars.totalBorrows = totalBorrows; _vars.totalReserves = totalReserves; // Gets the current borrow interest rate. _vars.borrowRate = interestRateModel.getBorrowRate( _vars.currentCash, _vars.totalBorrows, _vars.totalReserves ); require( _vars.borrowRate <= maxBorrowRate, "_updateInterest: Borrow rate is too high!" ); // Records the current block number. _vars.currentBlockNumber = block.number; // Calculates the number of blocks elapsed since the last accrual. _vars.blockDelta = _vars.currentBlockNumber.sub(accrualBlockNumber); /** * Calculates the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * newTotalBorrows = interestAccumulated + totalBorrows * newTotalReserves = interestAccumulated * reserveFactor + totalReserves * newBorrowIndex = simpleInterestFactor * borrowIndex + borrowIndex */ _vars.simpleInterestFactor = _vars.borrowRate.mul(_vars.blockDelta); _vars.interestAccumulated = _vars.simpleInterestFactor.rmul( _vars.totalBorrows ); _vars.newTotalBorrows = _vars.interestAccumulated.add( _vars.totalBorrows ); _vars.newTotalReserves = reserveRatio .rmul(_vars.interestAccumulated) .add(_vars.totalReserves); _vars.borrowIndex = borrowIndex; _vars.newBorrowIndex = _vars .simpleInterestFactor .rmul(_vars.borrowIndex) .add(_vars.borrowIndex); // Writes the previously calculated values into storage. accrualBlockNumber = _vars.currentBlockNumber; borrowIndex = _vars.newBorrowIndex; totalBorrows = _vars.newTotalBorrows; totalReserves = _vars.newTotalReserves; // Emits an `UpdateInterest` event. emit UpdateInterest( _vars.currentBlockNumber, _vars.interestAccumulated, _vars.newBorrowIndex, _vars.currentCash, _vars.newTotalBorrows, _vars.newTotalReserves ); } } struct MintLocalVars { uint256 exchangeRate; uint256 mintTokens; uint256 actualMintAmout; } /** * @dev User deposits token into the market and `_recipient` gets iToken. * @param _recipient The address of the user to get iToken. * @param _mintAmount The amount of the underlying token to deposit. */ function _mintInternal(address _recipient, uint256 _mintAmount) internal virtual { controller.beforeMint(address(this), _recipient, _mintAmount); MintLocalVars memory _vars; /** * Gets the current exchange rate and calculate the number of iToken to be minted: * mintTokens = mintAmount / exchangeRate */ _vars.exchangeRate = _exchangeRateInternal(); // Transfers `_mintAmount` from caller to contract, and returns the actual amount the contract // get, cause some tokens may be charged. _vars.actualMintAmout = _doTransferIn(msg.sender, _mintAmount); // Supports deflationary tokens. _vars.mintTokens = _vars.actualMintAmout.rdiv(_vars.exchangeRate); // Mints `mintTokens` iToken to `_recipient`. _mint(_recipient, _vars.mintTokens); controller.afterMint( address(this), _recipient, _mintAmount, _vars.mintTokens ); emit Mint(msg.sender, _recipient, _mintAmount, _vars.mintTokens); } /** * @notice This is a common function to redeem, so only one of `_redeemiTokenAmount` or * `_redeemUnderlyingAmount` may be non-zero. * @dev Caller redeems undelying token based on the input amount of iToken or underlying token. * @param _from The address of the account which will spend underlying token. * @param _redeemiTokenAmount The number of iTokens to redeem into underlying. * @param _redeemUnderlyingAmount The number of underlying tokens to receive. */ function _redeemInternal( address _from, uint256 _redeemiTokenAmount, uint256 _redeemUnderlyingAmount ) internal virtual { require( _redeemiTokenAmount > 0, "_redeemInternal: Redeem iToken amount should be greater than zero!" ); controller.beforeRedeem(address(this), _from, _redeemiTokenAmount); _burnFrom(_from, _redeemiTokenAmount); /** * Transfers `_redeemUnderlyingAmount` underlying token to caller. */ _doTransferOut(msg.sender, _redeemUnderlyingAmount); controller.afterRedeem( address(this), _from, _redeemiTokenAmount, _redeemUnderlyingAmount ); emit Redeem( _from, msg.sender, _redeemiTokenAmount, _redeemUnderlyingAmount ); } /** * @dev Caller borrows assets from the protocol. * @param _borrower The account that will borrow tokens. * @param _borrowAmount The amount of the underlying asset to borrow. */ function _borrowInternal(address payable _borrower, uint256 _borrowAmount) internal virtual { controller.beforeBorrow(address(this), _borrower, _borrowAmount); // Calculates the new borrower and total borrow balances: // newAccountBorrows = accountBorrows + borrowAmount // newTotalBorrows = totalBorrows + borrowAmount BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower]; borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add( _borrowAmount ); borrowSnapshot.interestIndex = borrowIndex; totalBorrows = totalBorrows.add(_borrowAmount); // Transfers token to borrower. _doTransferOut(_borrower, _borrowAmount); controller.afterBorrow(address(this), _borrower, _borrowAmount); emit Borrow( _borrower, _borrowAmount, borrowSnapshot.principal, borrowSnapshot.interestIndex, totalBorrows ); } /** * @notice Please approve enough amount at first!!! If not, * maybe you will get an error: `SafeMath: subtraction overflow` * @dev `_payer` repays `_repayAmount` tokens for `_borrower`. * @param _payer The account to pay for the borrowed. * @param _borrower The account with the debt being payed off. * @param _repayAmount The amount to repay (or -1 for max). */ function _repayInternal( address _payer, address _borrower, uint256 _repayAmount ) internal virtual returns (uint256) { controller.beforeRepayBorrow( address(this), _payer, _borrower, _repayAmount ); // Calculates the latest borrowed amount by the new market borrowed index. uint256 _accountBorrows = _borrowBalanceInternal(_borrower); // Transfers the token into the market to repay. uint256 _actualRepayAmount = _doTransferIn( _payer, _repayAmount > _accountBorrows ? _accountBorrows : _repayAmount ); // Calculates the `_borrower` new borrow balance and total borrow balances: // accountBorrows[_borrower].principal = accountBorrows - actualRepayAmount // newTotalBorrows = totalBorrows - actualRepayAmount // Saves borrower updates. BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower]; borrowSnapshot.principal = _accountBorrows.sub(_actualRepayAmount); borrowSnapshot.interestIndex = borrowIndex; totalBorrows = totalBorrows < _actualRepayAmount ? 0 : totalBorrows.sub(_actualRepayAmount); // Defense hook. controller.afterRepayBorrow( address(this), _payer, _borrower, _actualRepayAmount ); emit RepayBorrow( _payer, _borrower, _actualRepayAmount, borrowSnapshot.principal, borrowSnapshot.interestIndex, totalBorrows ); return _actualRepayAmount; } /** * @dev The caller repays some of borrow and receive collateral. * @param _borrower The account whose borrow should be liquidated. * @param _repayAmount The amount to repay. * @param _assetCollateral The market in which to seize collateral from the borrower. */ function _liquidateBorrowInternal( address _borrower, uint256 _repayAmount, address _assetCollateral ) internal virtual { require( msg.sender != _borrower, "_liquidateBorrowInternal: Liquidator can not be borrower!" ); // According to the parameter `_repayAmount` to see what is the exact error. require( _repayAmount != 0, "_liquidateBorrowInternal: Liquidate amount should be greater than 0!" ); // Accrues interest for collateral asset. Base _dlCollateral = Base(_assetCollateral); _dlCollateral.updateInterest(); controller.beforeLiquidateBorrow( address(this), _assetCollateral, msg.sender, _borrower, _repayAmount ); require( _dlCollateral.accrualBlockNumber() == block.number, "_liquidateBorrowInternal: Failed to update block number in collateral asset!" ); uint256 _actualRepayAmount = _repayInternal(msg.sender, _borrower, _repayAmount); // Calculates the number of collateral tokens that will be seized uint256 _seizeTokens = controller.liquidateCalculateSeizeTokens( address(this), _assetCollateral, _actualRepayAmount ); // If this is also the collateral, calls seizeInternal to avoid re-entrancy, // otherwise make an external call. if (_assetCollateral == address(this)) { _seizeInternal(address(this), msg.sender, _borrower, _seizeTokens); } else { _dlCollateral.seize(msg.sender, _borrower, _seizeTokens); } controller.afterLiquidateBorrow( address(this), _assetCollateral, msg.sender, _borrower, _actualRepayAmount, _seizeTokens ); emit LiquidateBorrow( msg.sender, _borrower, _actualRepayAmount, _assetCollateral, _seizeTokens ); } /** * @dev Transfers this token to the liquidator. * @param _seizerToken The contract seizing the collateral. * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iTokens to seize. */ function _seizeInternal( address _seizerToken, address _liquidator, address _borrower, uint256 _seizeTokens ) internal virtual { require( _borrower != _liquidator, "seize: Liquidator can not be borrower!" ); controller.beforeSeize( address(this), _seizerToken, _liquidator, _borrower, _seizeTokens ); /** * Calculates the new _borrower and _liquidator token balances, * that is transfer `_seizeTokens` iToken from `_borrower` to `_liquidator`. */ _transfer(_borrower, _liquidator, _seizeTokens); // Hook checks. controller.afterSeize( address(this), _seizerToken, _liquidator, _borrower, _seizeTokens ); } /** * @param _account The address whose balance should be calculated. */ function _borrowBalanceInternal(address _account) internal view virtual returns (uint256) { // Gets stored borrowed data of the `_account`. BorrowSnapshot storage borrowSnapshot = accountBorrows[_account]; // If borrowBalance = 0, return 0 directly. if (borrowSnapshot.principal == 0 || borrowSnapshot.interestIndex == 0) return 0; // Calculate new borrow balance with market new borrow index: // recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex return borrowSnapshot.principal.mul(borrowIndex).divup( borrowSnapshot.interestIndex ); } /** * @dev Calculates the exchange rate from the underlying token to the iToken. */ function _exchangeRateInternal() internal view virtual returns (uint256) { if (totalSupply == 0) { // This is the first time to mint, so current exchange rate is equal to initial exchange rate. return initialExchangeRate; } else { // exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply return _getCurrentCash().add(totalBorrows).sub(totalReserves).rdiv( totalSupply ); } } function updateInterest() external virtual returns (bool); /** * @dev EIP2612 permit function. For more details, please look at here: * https://eips.ethereum.org/EIPS/eip-2612 * @param _owner The owner of the funds. * @param _spender The spender. * @param _value The amount. * @param _deadline The deadline timestamp, type(uint256).max for max 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(_deadline >= block.timestamp, "permit: EXPIRED!"); uint256 _currentNonce = nonces[_owner]; bytes32 _digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _getChainId(), _value, _currentNonce, _deadline ) ) ) ); address _recoveredAddress = ecrecover(_digest, _v, _r, _s); require( _recoveredAddress != address(0) && _recoveredAddress == _owner, "permit: INVALID_SIGNATURE!" ); nonces[_owner] = _currentNonce.add(1); _approve(_owner, _spender, _value); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @dev Transfers this tokens to the liquidator. * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iTokens to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external virtual; /** * @notice Users are expected to have enough allowance and balance before calling. * @dev Transfers asset in. */ function _doTransferIn(address _sender, uint256 _amount) internal virtual returns (uint256); function exchangeRateStored() external view virtual returns (uint256); function borrowBalanceStored(address _account) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: 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.12; interface IFlashloanExecutor { function executeOperation( address reserve, uint256 amount, uint256 fee, bytes memory data ) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } 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 rounding. 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) } } } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./TokenAdmin.sol"; /** * @title dForce's lending Token ERC20 Contract * @author dForce */ abstract contract TokenERC20 is TokenAdmin { /** * @dev Transfers `_amount` tokens from `_sender` to `_recipient`. * @param _sender The address of the source account. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function _transferTokens( address _sender, address _recipient, uint256 _amount ) internal returns (bool) { require( _sender != _recipient, "_transferTokens: Do not self-transfer!" ); controller.beforeTransfer(address(this), _sender, _recipient, _amount); _transfer(_sender, _recipient, _amount); controller.afterTransfer(address(this), _sender, _recipient, _amount); return true; } //---------------------------------- //********* ERC20 Actions ********** //---------------------------------- /** * @notice Cause iToken is an ERC20 token, so users can `transfer` them, * but this action is only allowed when after transferring tokens, the caller * does not have a shortfall. * @dev Moves `_amount` tokens from caller to `_recipient`. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function transfer(address _recipient, uint256 _amount) public virtual override nonReentrant returns (bool) { return _transferTokens(msg.sender, _recipient, _amount); } /** * @notice Cause iToken is an ERC20 token, so users can `transferFrom` them, * but this action is only allowed when after transferring tokens, the `_sender` * does not have a shortfall. * @dev Moves `_amount` tokens from `_sender` to `_recipient`. * @param _sender The address of the source account. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override nonReentrant returns (bool) { _approve( _sender, msg.sender, // spender allowance[_sender][msg.sender].sub(_amount) ); return _transferTokens(_sender, _recipient, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./TokenEvent.sol"; /** * @title dForce's lending Token admin Contract * @author dForce */ abstract contract TokenAdmin is TokenEvent { //---------------------------------- //********* Owner Actions ********** //---------------------------------- modifier settleInterest() { // Accrues interest. _updateInterest(); require( accrualBlockNumber == block.number, "settleInterest: Fail to accrue interest!" ); _; } /** * @dev Sets a new controller. */ function _setController(IControllerInterface _newController) external virtual onlyOwner { IControllerInterface _oldController = controller; // Ensures the input address is a controller contract. require( _newController.isController(), "_setController: This is not the controller contract!" ); // Sets to new controller. controller = _newController; emit NewController(_oldController, _newController); } /** * @dev Sets a new interest rate model. * @param _newInterestRateModel The new interest rate model. */ function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external virtual onlyOwner { // Gets current interest rate model. IInterestRateModelInterface _oldInterestRateModel = interestRateModel; // Ensures the input address is the interest model contract. require( _newInterestRateModel.isInterestRateModel(), "_setInterestRateModel: This is not the rate model contract!" ); // Set to the new interest rate model. interestRateModel = _newInterestRateModel; emit NewInterestRateModel(_oldInterestRateModel, _newInterestRateModel); } /** * @dev Sets a new reserve ratio. */ function _setNewReserveRatio(uint256 _newReserveRatio) external virtual onlyOwner settleInterest { require( _newReserveRatio <= maxReserveRatio, "_setNewReserveRatio: New reserve ratio too large!" ); // Gets current reserve ratio. uint256 _oldReserveRatio = reserveRatio; // Sets new reserve ratio. reserveRatio = _newReserveRatio; emit NewReserveRatio(_oldReserveRatio, _newReserveRatio); } /** * @dev Sets a new flashloan fee ratio. */ function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external virtual onlyOwner settleInterest { require( _newFlashloanFeeRatio <= BASE, "setNewFlashloanFeeRatio: New flashloan ratio too large!" ); // Gets current reserve ratio. uint256 _oldFlashloanFeeRatio = flashloanFeeRatio; // Sets new reserve ratio. flashloanFeeRatio = _newFlashloanFeeRatio; emit NewFlashloanFeeRatio(_oldFlashloanFeeRatio, _newFlashloanFeeRatio); } /** * @dev Sets a new protocol fee ratio. */ function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external virtual onlyOwner settleInterest // nonReentrant { require( _newProtocolFeeRatio <= BASE, "_setNewProtocolFeeRatio: New protocol ratio too large!" ); // Gets current reserve ratio. uint256 _oldProtocolFeeRatio = protocolFeeRatio; // Sets new reserve ratio. protocolFeeRatio = _newProtocolFeeRatio; emit NewProtocolFeeRatio(_oldProtocolFeeRatio, _newProtocolFeeRatio); } /** * @dev Admin withdraws `_withdrawAmount` of the iToken. * @param _withdrawAmount Amount of reserves to withdraw. */ function _withdrawReserves(uint256 _withdrawAmount) external virtual onlyOwner settleInterest // nonReentrant { require( _withdrawAmount <= totalReserves && _withdrawAmount <= _getCurrentCash(), "_withdrawReserves: Invalid withdraw amount and do not have enough cash!" ); uint256 _oldTotalReserves = totalReserves; // Updates total amount of the reserves. totalReserves = totalReserves.sub(_withdrawAmount); // Transfers reserve to the owner. _doTransferOut(owner, _withdrawAmount); emit ReservesWithdrawn( owner, _withdrawAmount, totalReserves, _oldTotalReserves ); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function _updateInterest() internal virtual; /** * @dev Transfers underlying token out. */ function _doTransferOut(address payable _recipient, uint256 _amount) internal virtual; /** * @dev Total amount of reserves owned by this contract. */ function _getCurrentCash() internal view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./TokenStorage.sol"; /** * @title dForce's lending Token event Contract * @author dForce */ contract TokenEvent is TokenStorage { //---------------------------------- //********** User Events *********** //---------------------------------- event UpdateInterest( uint256 currentBlockNumber, uint256 interestAccumulated, uint256 borrowIndex, uint256 cash, uint256 totalBorrows, uint256 totalReserves ); event Mint( address sender, address recipient, uint256 mintAmount, uint256 mintTokens ); event Redeem( address from, address recipient, uint256 redeemiTokenAmount, uint256 redeemUnderlyingAmount ); /** * @dev Emits when underlying is borrowed. */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 accountInterestIndex, uint256 totalBorrows ); event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 accountInterestIndex, uint256 totalBorrows ); event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address iTokenCollateral, uint256 seizeTokens ); event Flashloan( address loaner, uint256 loanAmount, uint256 flashloanFee, uint256 protocolFee, uint256 timestamp ); //---------------------------------- //********** Owner Events ********** //---------------------------------- event NewReserveRatio(uint256 oldReserveRatio, uint256 newReserveRatio); event NewFlashloanFeeRatio( uint256 oldFlashloanFeeRatio, uint256 newFlashloanFeeRatio ); event NewProtocolFeeRatio( uint256 oldProtocolFeeRatio, uint256 newProtocolFeeRatio ); event NewFlashloanFee( uint256 oldFlashloanFeeRatio, uint256 newFlashloanFeeRatio, uint256 oldProtocolFeeRatio, uint256 newProtocolFeeRatio ); event NewInterestRateModel( IInterestRateModelInterface oldInterestRateModel, IInterestRateModelInterface newInterestRateModel ); event NewController( IControllerInterface oldController, IControllerInterface newController ); event ReservesWithdrawn( address admin, uint256 amount, uint256 newTotalReserves, uint256 oldTotalReserves ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../library/Initializable.sol"; import "../library/ReentrancyGuard.sol"; import "../library/Ownable.sol"; import "../library/ERC20.sol"; import "../interface/IInterestRateModelInterface.sol"; import "../interface/IControllerInterface.sol"; /** * @title dForce's lending Token storage Contract * @author dForce */ contract TokenStorage is Initializable, ReentrancyGuard, Ownable, ERC20 { //---------------------------------- //********* Token Storage ********** //---------------------------------- uint256 constant BASE = 1e18; /** * @dev Whether this token is supported in the market or not. */ bool public constant isSupported = true; /** * @dev Maximum borrow rate(0.1% per block, scaled by 1e18). */ uint256 constant maxBorrowRate = 0.001e18; /** * @dev Interest ratio set aside for reserves(scaled by 1e18). */ uint256 public reserveRatio; /** * @dev Maximum interest ratio that can be set aside for reserves(scaled by 1e18). */ uint256 constant maxReserveRatio = 1e18; /** * @notice This ratio is relative to the total flashloan fee. * @dev Flash loan fee rate(scaled by 1e18). */ uint256 public flashloanFeeRatio; /** * @notice This ratio is relative to the total flashloan fee. * @dev Protocol fee rate when a flashloan happens(scaled by 1e18); */ uint256 public protocolFeeRatio; /** * @dev Underlying token address. */ IERC20Upgradeable public underlying; /** * @dev Current interest rate model contract. */ IInterestRateModelInterface public interestRateModel; /** * @dev Core control of the contract. */ IControllerInterface public controller; /** * @dev Initial exchange rate(scaled by 1e18). */ uint256 constant initialExchangeRate = 1e18; /** * @dev The interest index for borrows of asset as of blockNumber. */ uint256 public borrowIndex; /** * @dev Block number that interest was last accrued at. */ uint256 public accrualBlockNumber; /** * @dev Total amount of this reserve borrowed. */ uint256 public totalBorrows; /** * @dev Total amount of this reserves accrued. */ uint256 public totalReserves; /** * @dev Container for user balance information written to storage. * @param principal User total balance with accrued interest after applying the user's most recent balance-changing action. * @param interestIndex The total interestIndex as calculated after applying the user's most recent balance-changing action. */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: userAddress -> assetAddress -> balance for borrows. */ mapping(address => BorrowSnapshot) internal accountBorrows; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf; mapping(address => uint256) public nonces; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 { 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; function __ReentrancyGuard_init() internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 { using SafeMathUpgradeable for uint256; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; /** * @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 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. */ function __ERC20_init( string memory name_, string memory symbol_, uint8 decimals_ ) internal { name = name_; symbol = symbol_; decimals = decimals_; } /** * @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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual 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}. * * 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 returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, allowance[sender][msg.sender].sub(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, allowance[msg.sender][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( msg.sender, spender, allowance[msg.sender][spender].sub(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"); balanceOf[sender] = balanceOf[sender].sub(amount); balanceOf[recipient] = balanceOf[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"); totalSupply = totalSupply.add(amount); balanceOf[account] = balanceOf[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"); balanceOf[account] = balanceOf[account].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance if caller is not the `account`. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller other than `msg.sender` must have allowance for ``accounts``'s tokens of at least * `amount`. */ function _burnFrom(address account, uint256 amount) internal virtual { if (msg.sender != account) _approve( account, msg.sender, allowance[account][msg.sender].sub(amount) ); _burn(account, 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"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev 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. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev 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. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); }
* @dev Caller borrows assets from the protocol. @param _borrower The account that will borrow tokens. @param _borrowAmount The amount of the underlying asset to borrow./ Calculates the new borrower and total borrow balances: newAccountBorrows = accountBorrows + borrowAmount newTotalBorrows = totalBorrows + borrowAmount Transfers token to borrower.
function _borrowInternal(address payable _borrower, uint256 _borrowAmount) internal virtual { controller.beforeBorrow(address(this), _borrower, _borrowAmount); BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower]; borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add( _borrowAmount ); borrowSnapshot.interestIndex = borrowIndex; totalBorrows = totalBorrows.add(_borrowAmount); _doTransferOut(_borrower, _borrowAmount); controller.afterBorrow(address(this), _borrower, _borrowAmount); emit Borrow( _borrower, _borrowAmount, borrowSnapshot.principal, borrowSnapshot.interestIndex, totalBorrows ); }
133,192
[ 1, 11095, 324, 280, 3870, 7176, 628, 326, 1771, 18, 225, 389, 70, 15318, 264, 1021, 2236, 716, 903, 29759, 2430, 18, 225, 389, 70, 15318, 6275, 1021, 3844, 434, 326, 6808, 3310, 358, 29759, 18, 19, 26128, 326, 394, 29759, 264, 471, 2078, 29759, 324, 26488, 30, 225, 394, 3032, 38, 280, 3870, 273, 2236, 38, 280, 3870, 397, 29759, 6275, 225, 394, 5269, 38, 280, 3870, 273, 2078, 38, 280, 3870, 397, 29759, 6275, 2604, 18881, 1147, 358, 29759, 264, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 70, 15318, 3061, 12, 2867, 8843, 429, 389, 70, 15318, 264, 16, 2254, 5034, 389, 70, 15318, 6275, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 565, 288, 203, 3639, 2596, 18, 5771, 38, 15318, 12, 2867, 12, 2211, 3631, 389, 70, 15318, 264, 16, 389, 70, 15318, 6275, 1769, 203, 203, 3639, 605, 15318, 4568, 2502, 29759, 4568, 273, 2236, 38, 280, 3870, 63, 67, 70, 15318, 264, 15533, 203, 3639, 29759, 4568, 18, 26138, 273, 389, 70, 15318, 13937, 3061, 24899, 70, 15318, 264, 2934, 1289, 12, 203, 5411, 389, 70, 15318, 6275, 203, 3639, 11272, 203, 3639, 29759, 4568, 18, 2761, 395, 1016, 273, 29759, 1016, 31, 203, 3639, 2078, 38, 280, 3870, 273, 2078, 38, 280, 3870, 18, 1289, 24899, 70, 15318, 6275, 1769, 203, 203, 3639, 389, 2896, 5912, 1182, 24899, 70, 15318, 264, 16, 389, 70, 15318, 6275, 1769, 203, 203, 3639, 2596, 18, 5205, 38, 15318, 12, 2867, 12, 2211, 3631, 389, 70, 15318, 264, 16, 389, 70, 15318, 6275, 1769, 203, 203, 3639, 3626, 605, 15318, 12, 203, 5411, 389, 70, 15318, 264, 16, 203, 5411, 389, 70, 15318, 6275, 16, 203, 5411, 29759, 4568, 18, 26138, 16, 203, 5411, 29759, 4568, 18, 2761, 395, 1016, 16, 203, 5411, 2078, 38, 280, 3870, 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 ]
pragma solidity 0.5.3; import './ICerticolCA.sol'; import './ICerticolDAOToken.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/IERC20.sol'; import 'openzeppelin-solidity/contracts/token/ERC777/IERC777Recipient.sol'; import 'openzeppelin-solidity/contracts/introspection/IERC1820Registry.sol'; /** * @title Certicol DAO Contract * * @author Ken Sze <[email protected]> * * @notice This contracts defines the Certicol DAO as specified in the Certicol protocol. * * @dev This token contract obeys the ERC-1820 standard and uses Orcalize. */ contract CerticolDAO is IERC777Recipient { /// Use safe math using SafeMath for uint256; /// Struct definition struct CerticolDAOVoC { uint256 blockIssue; uint256 tokenStaked; } /// ERC-1820 registry IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); /// ERC-777 interface hash for receiving tokens as a contract bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777TokensRecipient") /// CDT token interface that includes the mintInterest function ICerticolDAOToken private _CDT; /// ERC-20 interface of the CDT token IERC20 private _CDT_ERC20; /// Ownable interface of the CDT token Ownable private _CDT_Ownable; /// CerticolCA interface ICerticolCA private _CA; /// Mapping from address to tokens locked mapping(address => uint256) private _tokensLocked; /// Mapping from address to their voting rights /// Voting rights is automatically granted once the DAO received the tokens, /// but can also be delegated to another address mapping(address => uint256) private _votingRights; /// Mapping from address to their available PoSaT credit /// Similar to voting rights, PoSaT credit is automatically granted /// PoSaT credit can be consumed by either participating the PoSaT mechanism, /// thus locking the credit, or by delegating them to another address mapping(address => uint256) private _availablePoSaT; /// Mapping from address to their locked PoSaT credit, due to participation /// in the PoSaT mechanism /// It should be noted that delegation would NOT increase _lockedPoSaT, and /// the query on the net PoSaT credits an address have (available + delegated) /// should be done by getAvailablePoSaT() + getNetDelegatedPoSaT() mapping(address => uint256) private _lockedPoSaT; /// Cumulative tokens locked uint256 private _cumulativeTokenLocked = 0; /// Mapping from address to each delegated address and the amount of voting rights delegated mapping(address => mapping(address => uint256)) private _delegatedVotingRights; /// Mapping from address to the NET delegated voting rights to avoid secondary delegation mapping(address => uint256) private _delegatedNetVotingRights; /// Mapping from address to each delegated address and the amount of PoSaT credits delegated mapping(address => mapping(address => uint256)) private _delegatedPoSaT; /// Mapping from address to the NET delegated PoSaT credits to avoid secondary delegation mapping(address => uint256) private _delegatedNetPoSaT; /// CDT token requirement for granting O10 authorization, designated to be 10% of initial token supply uint256 private _O10Requirement; /// Mapping from address to their O10 authorization status and the amount of tokens locked mapping(address => uint256) private _O10Authorization; /// CDT token requirement for O10 vote of confidence (10,000 CDT) uint256 private _vocRequirement = uint256(10000).mul(uint256(10**18)); /// Mapping from O10 authorized address to total number of active PoSaT VoC records they have given out mapping(address => uint256) private _vocCount; /// Mapping from O10 authorized address to adress that they have voted confidence mapping(address => mapping(address => CerticolDAOVoC)) private _vocRecords; /// Reverse mappng from address being voted to an array of O10 authorized address that has voted confidence toward it mapping(address => address[]) private _vocReverseRecords; /// Proof-of-Stake-as-Trust reward ratio (5% p.a. as default) uint256 private _posatRewardRatio = 5; /// Proof-of-Stake-as-Trust reward block requirement (roughly 1 year as default) uint256 internal _posatRewardRequirement = 2102400; /// Cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status uint256 private _ringOneRequirement = 25; // Mapping that stored all used one-time seed used in previous O5 command to prevent reuse of those signatures mapping(uint256 => bool) private _usedOneTimeSeeds; /// Boolean that store whether this DAO is currently active bool private _DAODissolved = false; // Mapping that stored record of vote of confidence issued by O5 command mapping(address => bool) private _O5VoteNoConfidence; /// Event that will be emitted when tokens are received and locked within this contract event TokensLocked(address indexed tokenHolder, uint256 amount); /// Event that will be emitted when locked tokens are withdrawl event TokensUnlocked(address indexed tokenHolder, uint256 amount); /// Event that will be emitted upon delegation of voting rights event VotingRightsDelegation(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon the withdrawl of delegated voting rights event VotingRightsDelegationWithdrawl(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon delegation of free PoSaT credits event PoSaTDelegation(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon the withdrawl of delegated PoSaT credits event PoSaTDelegationWithdrawl(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event emitted when O10 authorization is given out event O10Authorized(address indexed O10, uint256 PoSaTLocked); /// Event emitted when O10 authotization is revoked event O10Deauthorized(address indexed O10, uint256 PoSaTUnlocked); /// Event emitted when O10 voted confidence event O10VotedConfidence(address indexed O10, address indexed target, uint256 PoSaTLocked); /// Event emitted when O10 was granted reward for PoSaT event O10RewardGranted(address indexed O10, uint256 reward); /// Event emitted when O10 revoke the vote of confidence event O10RevokeVoteConfidence(address indexed O10, address indexed target, uint256 PoSaTUnlocked); /// Event emitted when O5 is authorized event O5Authorized(string indexed functionSignatureIndex, string functionSignature, address[5] O5, uint256 cumulativeVote); /// Event emitted when O5 amends the cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status event O5AmendRingOneRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the PoSaT reward requirement event O5AmendPoSaTRewardRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the Proof-of-Stake-as-Trust reward ratio event O5AmendPoSaTReward(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the CDT token requirement for O10 vote of confidence event O5AmendVoCRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the CDT token requirement for granting O10 authorization event O5AmendO10Requirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 dissolve this DAO event O5DissolvedDAO(uint256 effectiveFrom); /// Event emitted when O5 voted no confidence toward target event O5VotedNoConfidence(address indexed target); /** * @notice Initialize the CerticolDAO contract * @param tokenAddress address the address of the deployed CerticolDAOToken contract * @param caAddress address the address of the deployed CerticolCA contract */ constructor(address tokenAddress, address caAddress) public { // Register ERC-777 RECIPIENT_INTERFACE at ERC-1820 registry _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); // Initialize CDT token interface _CDT = ICerticolDAOToken(tokenAddress); _CDT_ERC20 = IERC20(tokenAddress); _CDT_Ownable = Ownable(tokenAddress); // Initialize O10 requirements _O10Requirement = _CDT_ERC20.totalSupply().div(10); // Initialize CerticolCA interface _CA = ICerticolCA(caAddress); } /** * @notice Get the number of tokens locked for holder * @param holder address the address queried * @return uint256 the number of tokens locked */ function getTokensLocked(address holder) public view returns (uint256) { return _tokensLocked[holder]; } /** * @notice Get the voting rights owned by holder * @param holder address the address queried * @return uint256 the number of voting rights owned */ function getVotingRights(address holder) public view returns (uint256) { return _votingRights[holder]; } /** * @notice Get the available PoSaT credit owned by holder * @param holder address the address queried * @return uint256 the available PoSaT credit owned */ function getAvailablePoSaT(address holder) public view returns (uint256) { return _availablePoSaT[holder]; } /** * @notice Get the locked PoSaT credit owned by holder * @param holder address the address queried * @return uint256 the locked PoSaT credit owned */ function getLockedPoSaT(address holder) public view returns (uint256) { return _lockedPoSaT[holder]; } /** * @notice Get the net amount of token locked in this contract * @return the net amount of token locked in this contract */ function getCumulativeTokenLocked() public view returns (uint256) { return _cumulativeTokenLocked; } /** * @notice Get the amount of delegated voting rights from tokenHolder to delegate * @param tokenHolder address the address which has their tokens locked * @param delegate address the address of the delegate * @return uint256 the amount of delegated voting rights from tokenHolder to delegate */ function getDelegatedVotingRights(address tokenHolder, address delegate) public view returns (uint256) { return _delegatedVotingRights[tokenHolder][delegate]; } /** * @notice Get the net amount of delegated voting rights from tokenHolder to all delegate(s) * @param tokenHolder address the address which has their tokens locked * @return uint256 the net amount of delegated voting rights from tokenHolder to all delegate(s) */ function getNetDelegatedVotingRights(address tokenHolder) public view returns (uint256) { return _delegatedNetVotingRights[tokenHolder]; } /** * @notice Get the amount of delegated PoSaT credits from tokenHolder to delegate * @param tokenHolder address the address which has their tokens locked * @param delegate address the address of the delegate * @return uint256 tthe amount of delegated PoSaT credits from tokenHolder to delegate */ function getDelegatedPoSaT(address tokenHolder, address delegate) public view returns (uint256) { return _delegatedPoSaT[tokenHolder][delegate]; } /** * @notice Get the net amount of delegated PoSaT credits from tokenHolder to all delegate(s) * @param tokenHolder address the address which has their tokens locked * @return uint256 the net amount of delegated PoSaT credits from tokenHolder to all delegate(s) */ function getNetDelegatedPoSaT(address tokenHolder) public view returns (uint256) { return _delegatedNetPoSaT[tokenHolder]; } /** * @notice Get the amount of available PoSaT credits required for O10 authorization * @return uint256 the amount of available PoSaT credits required for O10 authorization */ function getO10Requirements() public view returns (uint256) { return _O10Requirement; } /** * @notice Get the O10 authorization status of an address * @param query address the address to be queried * @return bool true if query owns O10 authorization status and false if doesn't */ function getO10Status(address query) public view returns (bool) { return _O10Authorization[query] != 0; } /** * @notice Get the available PoSaT credits requirement for voting confidence * @return bool the available PoSaT credits requirement for voting confidence */ function getVOCRequirement() public view returns (uint256) { return _vocRequirement; } /** * @notice Get the total number of active PoSaT vote of confidence issued by the O10 member * @param O10 address the address of the O10 to be queried * @return uint256 the total number of active PoSaT vote of confidence issued by the O10 member */ function getActiveVoCIssued(address O10) public view returns (uint256) { return _vocCount[O10]; } /** * @notice Get a list of O10 that has voted confidence toward target * @param target address the address to be queried on what O10 has voted confidence on it * @return address[] list of O10 that has voted confidence toward target * @dev address(0) could be returned in the array, which is an leftover from a revoke of vote of confidence */ function getVoC(address target) public view returns (address[] memory) { return _vocReverseRecords[target]; } /** * @notice Get whether a O10 has voted confidence toward target * @param target address the address to be queried on whether O10 has voted confidence on it * @param O10 address the address of the O10 to be queried * @return bool true if O10 has voted confidence, and false if otherwise */ function getVoCFrom(address target, address O10) public view returns (bool) { return _vocRecords[O10][target].blockIssue != 0; } /** * @notice Get the current Proof-of-Stake-as-Trust reward ratio * @return uint256 the current Proof-of-Stake-as-Trust reward ratio */ function getCurrentPoSaTReward() public view returns (uint256) { return _posatRewardRatio; } /** * @notice Get the current Proof-of-Stake-as-Trust reward block requirement * @return uint256 the current Proof-of-Stake-as-Trust reward block requirement */ function getCurrentPoSaTRequirement() public view returns (uint256) { return _posatRewardRequirement; } /** * @notice Get the current cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status * @return uint256 the current cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status */ function getCurrentRingOneRequirement() public view returns (uint256) { return _ringOneRequirement; } /** * @notice Get the current ring of validation for target * @param target address the address to be queried * @return uint256 either 1, 2, 3 or 4 which corresponds to the ring of validation * @dev Ring one validation is granted if target owns a valid ring 2 status * @dev And, in addition, cumulative PoSaT credits owned by O10 who have voted confidence > _ringOneRequirement of total supply * @dev If O5 has voted no confidence toward target, only 4 would be returned */ function getCurrentRing(address target) external view returns (uint256) { // Check if O5 has voted no confidence if (_O5VoteNoConfidence[target]) { // Return 4 if O5 has voted no confidence return 4; } // Get ring 2 - 4 validation status from CerticolCA (uint256 ring,,) = _CA.getStatus(target); // Return ring 3 - 4 validation status since no further computation is required if (ring > 2) { return ring; } // Compute if target qualifies for ring 1 validation // Calculate the total PoSaT credits held by O10 who have voted confidence (inc. available and locked credits) uint256 totalTokenHeld = 0; for (uint256 i = 0; i<_vocReverseRecords[target].length; i++) { address currentO10 = _vocReverseRecords[target][i]; // Skip if current address is address(0) - leftover from revoking vote of confidence if (currentO10 != address(0)) { totalTokenHeld = totalTokenHeld.add(_availablePoSaT[currentO10]).add(_lockedPoSaT[currentO10]); } } // Validate if all O10 that has voted confidence toward target have a summation of 25% tokens locked if (totalTokenHeld.mul(100).div(_ringOneRequirement) >= _cumulativeTokenLocked) { return 1; // Ring 1 status } else { return 2; // Ring 2 status } } /** * @notice Get if the given seed was already used in a previous O5 command * @return bool true if the seed was used before, or false if otherwise */ function getSeedUsed(uint256 seed) external view returns (bool) { return _usedOneTimeSeeds[seed]; } /** * @notice Get if the current DAO has been dissolved * @return bool true if the current DAO has been dissolved, or false if otherwise */ function getDAODissolved() external view returns (bool) { return _DAODissolved; } /** * @notice Get whether O5 has voted no confidence toward target * @param target address the address to be queried * @return boolean true if O5 has voted no confidence, false if not */ function getO5VoteNoConfidence(address target) external view returns (bool) { return _O5VoteNoConfidence[target]; } /** * @notice Throws if O5 has dissolved this DAO */ modifier DAOFunctional() { // Require dissolved flag to be false require(!_DAODissolved, "CerticolDAO: this function is no longer available since O5 has dissolved this DAO"); _; } /** * @notice Implements the IERC777Recipient interface to allow this contract to receive CDT token * @dev Any inward transaction of ERC-777 other than CDT token would be reverted * @param from address token holder address * @param amount uint256 amount of tokens to transfer * @dev Reverts if O5 has dissolved the current DAO */ function tokensReceived(address, address from, address, uint256 amount, bytes calldata, bytes calldata) external DAOFunctional { // Only accept inward ERC-777 transaction if it is the CDT token require(msg.sender == address(_CDT), "CerticolDAO: we only accept CDT token"); // Modify the internal state upon receiving the tokens _tokensLocked[from] = _tokensLocked[from].add(amount); _votingRights[from] = _votingRights[from].add(amount); _availablePoSaT[from] = _availablePoSaT[from].add(amount); _cumulativeTokenLocked = _cumulativeTokenLocked.add(amount); // Emit TokensLocked event emit TokensLocked(from, amount); } /** * @notice Allow msg.sender to withdraw locked token * @dev This function will only proceeds if the msg.sender owns 1 voting rights and 1 free PoSaT credit per 1 token withdrawl, * and would otherwise reverts * @param amount uint256 amount of tokens to withdraw * @dev Reverts if O5 has dissolved the current DAO */ function withdrawToken(uint256 amount) external DAOFunctional { // Subtract amount from _votingRights and _availablePoSaT _votingRights[msg.sender] = _votingRights[msg.sender].sub(amount); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(amount); // Successfully subtracted their voting rights and PoSaT credit // Proceed with the withdrawl _tokensLocked[msg.sender] = _tokensLocked[msg.sender].sub(amount); _cumulativeTokenLocked = _cumulativeTokenLocked.sub(amount); // Emit TokensUnlocked event emit TokensUnlocked(msg.sender, amount); // Transfer token to msg.sender _CDT_ERC20.transfer(msg.sender, amount); } /** * @notice Delegate voting rights from msg.sender to a specific delegate * @dev This function will only proceeds if the msg.sender owns sufficient voting rights, * and if total voting rights delegated after operation would not exceeds the amount of tokens locked * to avoid secondary delegation * @param delegate address address of the delegate * @param amount uint256 amount of voting rights to delegate * @dev Reverts if O5 has dissolved the current DAO */ function delegateVotingRights(address delegate, uint256 amount) external DAOFunctional { // Check if total voting rights delegated after operation would exceeds the amount of tokens require( _delegatedNetVotingRights[msg.sender].add(amount) <= _tokensLocked[msg.sender], "CerticolDAO: insufficient voting rights or secondary delegation is not permitted" ); // Transfer voting rights to delegate _votingRights[msg.sender] = _votingRights[msg.sender].sub(amount); _votingRights[delegate] = _votingRights[delegate].add(amount); // Add the delegate record to _delegatedVotingRights and _delegatedNetVotingRights _delegatedVotingRights[msg.sender][delegate] = _delegatedVotingRights[msg.sender][delegate].add(amount); _delegatedNetVotingRights[msg.sender] = _delegatedNetVotingRights[msg.sender].add(amount); // Emit VotingRightsDelegation emit VotingRightsDelegation(msg.sender, delegate, amount); } /** * @notice Withdraw delegated voting rights from a specific delegate * @dev This function will reverts if amount > voting rights delegated to the delegate * @param delegate address address of the delegate * @param amount uint256 amount of delegated voting rights to withdraw from the delegate * @dev Reverts if O5 has dissolved the current DAO */ function withdrawDelegatedVotingRights(address delegate, uint256 amount) external DAOFunctional { // Reduce the amount from _delegatedVotingRights and _delegatedNetVotingRights // This will also revert if amount exceeds the voting rights initially delegated _delegatedVotingRights[msg.sender][delegate] = _delegatedVotingRights[msg.sender][delegate].sub(amount); _delegatedNetVotingRights[msg.sender] = _delegatedNetVotingRights[msg.sender].sub(amount); // Transfer voting rights back to msg.sender _votingRights[delegate] = _votingRights[delegate].sub(amount); _votingRights[msg.sender] = _votingRights[msg.sender].add(amount); // Emit VotingRightsDelegationWithdrawl emit VotingRightsDelegationWithdrawl(msg.sender, delegate, amount); } /** * @notice Delegate PoSaT credits from msg.sender to a specific delegate * @dev This function will only proceeds if the msg.sender owns sufficient FREE PoSaT credits, * and if total voting rights delegated after operation would not exceeds the amount of tokens locked * to avoid secondary delegation * @param delegate address address of the delegate * @param amount uint256 amount of voting rights to delegate * @dev Reverts if O5 has dissolved the current DAO */ function delegatePoSaT(address delegate, uint256 amount) external DAOFunctional { // Check if total PoSaT delegated after operation would exceeds the amount of tokens require( _delegatedNetPoSaT[msg.sender].add(amount) <= _tokensLocked[msg.sender], "CerticolDAO: insufficient PoSaT credits or secondary delegation is not permitted" ); // Transfer free PoSaT credits to delegate _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(amount); _availablePoSaT[delegate] = _availablePoSaT[delegate].add(amount); // Add the delegate record to _delegatedPoSaT and _delegatedNetPoSaT _delegatedPoSaT[msg.sender][delegate] = _delegatedPoSaT[msg.sender][delegate].add(amount); _delegatedNetPoSaT[msg.sender] = _delegatedNetPoSaT[msg.sender].add(amount); // Emit PoSaTDelegation emit PoSaTDelegation(msg.sender, delegate, amount); } /** * @notice Withdraw delegated PoSaT credits from a specific delegate * @dev This function will reverts if amount > PoSaT credits delegated to the delegate, * or if the delegate does not have the required FREE PoSaT credits * @param delegate address address of the delegate * @param amount uint256 amount of delegated voting rights to withdraw from the delegate * @dev Reverts if O5 has dissolved the current DAO */ function withdrawDelegatedPoSaT(address delegate, uint256 amount) external DAOFunctional { // Reduce the amount from _delegatedPoSaT and _delegatedNetPoSaT // This will also revert if amount exceeds the PoSaT credits initially delegated _delegatedPoSaT[msg.sender][delegate] = _delegatedPoSaT[msg.sender][delegate].sub(amount); _delegatedNetPoSaT[msg.sender] = _delegatedNetPoSaT[msg.sender].sub(amount); // Transfer PoSaT credits back to msg.sender // Unlike voting rights, PoSaT credits can be locked by the delegate by participating in the PoSaT mechanism // The withdrawl of delegated PoSaT credits will only work if the delegate has sufficient free PoSaT credits _availablePoSaT[delegate] = _availablePoSaT[delegate].sub(amount); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(amount); // Emit PoSaTDelegationWithdrawl emit PoSaTDelegationWithdrawl(msg.sender, delegate, amount); } /** * @notice Throws if msg.sender do not have O10 authorization */ modifier O10Only() { require(getO10Status(msg.sender), "CerticolDAO: msg.sender did not owned a valid O10 authorization"); _; } /** * @notice Throws if O5 has voted no confidence toward target */ modifier O5NotVotedNoConfidence(address target) { require(!_O5VoteNoConfidence[target], "CerticolDAO: O5 has voted no confidence toward the target"); _; } /** * @notice Lock _O10Requirement PoSaT credits and grants msg.sender O10 authorization * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if msg.sender does not have sufficient available PoSaT credits * @dev Reverts if msg.sender have O10 authorization already */ function O10Authorization() external DAOFunctional { // Check if msg.sender already have O10 authorization require(!getO10Status(msg.sender), "CerticolDAO: msg.sender already owned a valid O10 authorization"); // Lock _O10Requirement PoSaT credits _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(_O10Requirement); _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].add(_O10Requirement); // Grant O10 authorization _O10Authorization[msg.sender] = _O10Requirement; // Emit O10Authorized emit O10Authorized(msg.sender, _O10Requirement); } /** * @notice Revoke msg.sender O10 authorization and unlock locked PoSaT credits * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender still have active PoSaT VoC issued currently * @dev O10 can ONLY be deauthorized after all PoSaT VoC issued by msg.sender has been revoked */ function O10Deauthorization() external DAOFunctional O10Only { // Check if msg.sender still has any active PoSaT VoC require(getActiveVoCIssued(msg.sender) == 0, "CerticolDAO: msg.sender still has active PoSaT VoC"); // Unlock _O10Requirement PoSaT credits uint256 lockedCredit = _O10Authorization[msg.sender]; _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].sub(lockedCredit); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(lockedCredit); // Revoke O10 authorization _O10Authorization[msg.sender] = 0; // Emit O10Deauthorized emit O10Deauthorized(msg.sender, lockedCredit); } /** * @notice Lock required amounts of PoSaT credits and vote confidence toward target * @param target address the address to be voted confidence on * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have already voted confidence toward target * @dev Reverts if msg.sender do not have sufficient available PoSaT credits */ function O10VoteConfidence(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has already voted confidence toward target require(!getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has already voted confidence toward target"); // Subtract required PoSaT credits from msg.sender _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(_vocRequirement); _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].add(_vocRequirement); // Adds to active PoSaT VoC _vocCount[msg.sender] = _vocCount[msg.sender].add(1); // Appends the record to VoC records _vocRecords[msg.sender][target] = CerticolDAOVoC(block.number, _vocRequirement); // Appends to reverse records as well _vocReverseRecords[target].push(msg.sender); // Emit O10VotedConfidence emit O10VotedConfidence(msg.sender, target, _vocRequirement); } /** * @notice Get PoSaT reward from a vote of confidence issued to target * @param target address the address that msg.sender have voted confidence on, and would like to get the PoSaT reward from the vote * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have not voted confidence toward target * @dev Reverts if the vote has not been sustained for a minimum of _posatRewardRequirement blocks * @dev Reverts if the target has not sustained ring 2 status from CerticolCA for a minimum of _posatRewardRequirement blocks */ function O10GetReward(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has actually voted confidence toward target require(getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has not voted confidence toward target"); // Check if the vote has sustained for _posatRewardRequirement blocks require( block.number.sub(_vocRecords[msg.sender][target].blockIssue) >= _posatRewardRequirement, "CerticolDAO: vote of confidence has not sustained long enough for reward" ); // Check if the Ring 2 validation has sustained throughout this period (,uint256 ring2IssueBlock,) = _CA.getStatus(target); require(ring2IssueBlock != 0, "CerticolDAO: target has no ring 2 status"); require( block.number.sub(ring2IssueBlock) >= _posatRewardRequirement, "CerticolDAO: ring 2 status has not sustained long enough for reward" ); // Calculate the reward to be minted (tokenStaked * _posatRewardRatio / 100) uint256 reward = _vocRecords[msg.sender][target].tokenStaked.mul(_posatRewardRatio).div(100); // Before reward is minted, increment blockIssue in CerticolDAOVoC record _vocRecords[msg.sender][target].blockIssue = _vocRecords[msg.sender][target].blockIssue.add(_posatRewardRequirement); // Emit O10RewardGranted emit O10RewardGranted(msg.sender, reward); // Mint the reward _CDT.mintInterest(msg.sender, reward); } /** * @notice Revoke vote of confidence and unlock the locked PoSaT credits * @param target address the address that msg.sender have voted confidence on, and would like to revoke the vote * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have not voted confidence toward target */ function O10RevokeVote(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has actually voted confidence toward target require(getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has not voted confidence toward target"); // Delete reverse vote entry in _vocReverseRecords for (uint256 i = 0; i<_vocReverseRecords[target].length; i++) { if (_vocReverseRecords[target][i] == msg.sender) { delete _vocReverseRecords[target][i]; break; } } // Delete vote entry in _vocRecords uint256 tokenLocked = _vocRecords[msg.sender][target].tokenStaked; delete _vocRecords[msg.sender][target]; // Subtract 1 from active PoSaT VoC _vocCount[msg.sender] = _vocCount[msg.sender].sub(1); // Unlock the locked PoSaT credits _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].sub(tokenLocked); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(tokenLocked); // Emit O10RevokeVoteConfidence emit O10RevokeVoteConfidence(msg.sender, target, tokenLocked); } /** * @notice O5 authorization check * @param fnSignature string the function signature * @param amendedValue uint256 the new PoSaT reward requirement * @param effectiveBlock uint256 the block number signed by O5 members in signature * @param oneTimeSeed uint256 an one-time seed used to prevent reuse of published signatures * @param v uint[5] v component of up to 5 signatures * @param r bytes32[5] r component of up to 5 signatures * @param s bytes32[5] s component of up to 5 signatures * @dev Reverts if effectiveBlock > block.number, which indicate the signature has already expired * @dev Reverts if cumulative voting rights in all signatures did not exceeds 50% of all voting rights */ modifier O5Only( string memory fnSignature, uint256 amendedValue, uint256 effectiveBlock, uint256 oneTimeSeed, uint8[5] memory v, bytes32[5] memory r, bytes32[5] memory s ) { // Check if signature would still be valid (i.e. effectiveBlock > block.number) require(effectiveBlock > block.number, "CerticolDAO: signature has expired"); // Check if oneTimeSeed was used in the past require(!_usedOneTimeSeeds[oneTimeSeed], "CerticolDAO: the seed was already used"); // Ethereum signature prefix bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // Expected message to be signed would be sha3(fnSignature, amendedValue, effectiveBlock, oneTimeSeed) bytes32 expectedMessage = keccak256(abi.encodePacked(fnSignature, amendedValue, effectiveBlock, oneTimeSeed)); // Expected actual hash signed to be sha3(prefix, message) bytes32 expectedHash = keccak256(abi.encodePacked(prefix, expectedMessage)); // List of O5s that have voted this authorization address[5] memory O5s; // Cumulative voting rights that has signed the message uint256 netVotingRights = 0; // Loop through v, r, s arrays to recover signing address and sum their voting right for (uint256 i = 0; i<5; i++) { // Extract address of the voter address O5 = ecrecover(expectedHash, v[i], r[i], s[i]); // Ensure no repeated signature is submitted for (uint256 j = 0; j < i; j++) { if (O5 == O5s[j]) { // Repeated signature found, reset O5 to address(0) as no processing is required O5 = address(0); break; } } // Process only if O5 is not address(0) if (O5 != address(0)) { // Record to the list of O5s O5s[i] = O5; // Adds to cumulative voting rights netVotingRights = netVotingRights.add(_votingRights[O5]); } } // Check if cumulative voting rights exceeds 50% of total voting rights require( netVotingRights >= _cumulativeTokenLocked.div(2), "CerticolDAO: cumulative voting rights did not exceeds 50% of total voting rights" ); // Updated used seed mapping _usedOneTimeSeeds[oneTimeSeed] = true; // Emit O5Authorized emit O5Authorized(fnSignature, fnSignature, O5s, netVotingRights); // Proceed if true _; } /** * @notice O5 command to modify CerticolDAO variables * @param effectiveBlock uint256 the block number signed by O5 members in signature * @param oneTimeSeed uint256 an one-time seed used to prevent reuse of published signatures * @param v uint[5] v component of up to 5 signatures * @param r bytes32[5] r component of up to 5 signatures * @param s bytes32[5] s component of up to 5 signatures * @param fnSignature string O5 command string * @param amendedValue uint256 the new ring one requirement * @dev Reverts if O5 check failed */ function O5Command( uint256 effectiveBlock, uint256 oneTimeSeed, uint8[5] calldata v, bytes32[5] calldata r, bytes32[5] calldata s, string calldata fnSignature, uint256 amendedValue ) external O5Only(fnSignature, amendedValue, effectiveBlock, oneTimeSeed, v, r, s) { bytes32 fnSignatureHash = keccak256(abi.encodePacked(fnSignature)); if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyRingOneRequirement"))) { // Change the ring one requirement _ringOneRequirement = amendedValue; // Emit O5AmendRingOneRequirement emit O5AmendRingOneRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyPoSaTRequirement"))) { // Change the reward requirement _posatRewardRequirement = amendedValue; // Emit O5AmendPoSaTRewardRequirement emit O5AmendPoSaTRewardRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyPoSaTReward"))) { // Change the PoSaT reward ratio _posatRewardRatio = amendedValue; // Emit O5AmendPoSaTReward emit O5AmendPoSaTReward(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyVoCRequirement"))) { // Change the VoC Requirement _vocRequirement = amendedValue; // Emit O5AmendVoCRequirement emit O5AmendVoCRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyO10Requirement"))) { // Change the O10 Requirement _O10Requirement = amendedValue; // Emit O5AmendO10Requirement emit O5AmendO10Requirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5DissolveDAO"))) { // Set dissolved falg _DAODissolved = true; // Transfer ownership of CerticolDAOToken _CDT_Ownable.transferOwnership(msg.sender); // Emit O5DissolvedDAO emit O5DissolvedDAO(block.number); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5VoteNoConfidence"))) { // Cast uint256 back to address address target = address(amendedValue); // Update the _O5VoteNoConfidence mapping _O5VoteNoConfidence[target] = true; // Emit O5VotedNoConfidence emit O5VotedNoConfidence(target); } else { return; } } /** * @notice Allow the withdrawl of all token locked in this contract after O5 has dissolved this DAO * @dev Reverts if this DAO has not been dissolved */ function dissolveWithdrawl() external { // Require dissolved flag require(_DAODissolved, "CerticolDAO: this function is only available if O5 has dissolved this DAO"); // Get total amount of token locked by msg.sender uint256 tokenLocked = _tokensLocked[msg.sender]; // Reset tokensLocked mapping _tokensLocked[msg.sender] = 0; // Reduce cumulative token locked respectively _cumulativeTokenLocked = _cumulativeTokenLocked.sub(tokenLocked); // Emit TokensUnlocked emit TokensUnlocked(msg.sender, tokenLocked); // Withdraw all token locked _CDT_ERC20.transfer(msg.sender, tokenLocked); } }
Event emitted when O10 voted confidence
event O10VotedConfidence(address indexed O10, address indexed target, uint256 PoSaTLocked);
13,141,374
[ 1, 1133, 17826, 1347, 531, 2163, 331, 16474, 15588, 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, 871, 531, 2163, 58, 16474, 3976, 10328, 12, 2867, 8808, 531, 2163, 16, 1758, 8808, 1018, 16, 2254, 5034, 453, 31605, 69, 56, 8966, 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 ]
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsStable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } pragma solidity ^0.6.0; interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.6.0; library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } pragma solidity ^0.6.0; contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } pragma solidity ^0.6.0; abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } pragma solidity ^0.6.0; import "./Gem.sol"; abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } pragma solidity ^0.6.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } pragma solidity ^0.6.0; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { 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 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); } /** * @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 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 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 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; } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } pragma solidity ^0.6.0; abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } pragma solidity ^0.6.0; /// @title Implements enum Method abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } pragma solidity ^0.6.0; abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr) ); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } pragma solidity ^0.6.0; abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve DSProxy to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; uint borrowCap; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]), borrowCap: comp.borrowCaps(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1500000; uint public BOOST_GAS_COST = 1000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); }
@notice Return a rate for which we can sell an amount of tokens @param _srcAddr From token @param _destAddr To token @param _srcAmount From amount @return rate Rate multiply with decimal difference in src token divide with decimal difference in dest token
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); rate = rate * (10**(18 - getDecimals(_srcAddr))); rate = rate / (10**(18 - getDecimals(_destAddr))); }
380,909
[ 1, 990, 279, 4993, 364, 1492, 732, 848, 357, 80, 392, 3844, 434, 2430, 225, 389, 4816, 3178, 6338, 1147, 225, 389, 10488, 3178, 2974, 1147, 225, 389, 4816, 6275, 6338, 3844, 327, 4993, 13025, 10194, 598, 6970, 7114, 316, 1705, 1147, 12326, 598, 6970, 7114, 316, 1570, 1147, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1322, 1165, 4727, 12, 2867, 389, 4816, 3178, 16, 1758, 389, 10488, 3178, 16, 2254, 389, 4816, 6275, 13, 1071, 3849, 1476, 1135, 261, 11890, 4993, 13, 288, 203, 3639, 261, 5141, 16, 262, 273, 1475, 93, 744, 3906, 3886, 1358, 12, 47, 61, 6271, 67, 18865, 13, 203, 5411, 263, 588, 6861, 4727, 12, 654, 39, 3462, 24899, 4816, 3178, 3631, 4232, 39, 3462, 24899, 10488, 3178, 3631, 389, 4816, 6275, 1769, 203, 203, 3639, 4993, 273, 4993, 380, 261, 2163, 636, 12, 2643, 300, 336, 31809, 24899, 4816, 3178, 3719, 1769, 203, 3639, 4993, 273, 4993, 342, 261, 2163, 636, 12, 2643, 300, 336, 31809, 24899, 10488, 3178, 3719, 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 ]
./partial_match/1/0x5435Fc74aeD67C81BB500490A4365AF5e6021bba/sources/StrategySushiLpOptimizer.sol
===== View Functions =====
function baseStrategyVersion() public view returns (string memory) { return "1.1"; }
2,604,561
[ 1, 894, 33, 4441, 15486, 422, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1026, 4525, 1444, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 21, 18, 21, 14432, 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, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // Part: IBasicRewards interface IBasicRewards { function stakeFor(address, uint256) external returns (bool); function balanceOf(address) external view returns (uint256); function earned(address) external view returns (uint256); function withdrawAll(bool) external returns (bool); function withdraw(uint256, bool) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function getReward() external returns (bool); function stake(uint256) external returns (bool); function extraRewards(uint256) external view returns (address); } // Part: IBooster interface IBooster { function depositAll(uint256 _pid, bool _stake) external returns (bool); function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); } // Part: ICVXLocker interface ICVXLocker { function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function balances(address _user) external view returns ( uint112 locked, uint112 boosted, uint32 nextUnlockIndex ); } // Part: ICurveFactoryPool interface ICurveFactoryPool { function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_balances() external view returns (uint256[2] memory); function add_liquidity( uint256[2] memory _amounts, uint256 _min_mint_amount, address _receiver ) external returns (uint256); function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy, address _receiver ) external returns (uint256); } // Part: ICurveTriCrypto interface ICurveTriCrypto { function exchange( uint256 i, uint256 j, uint256 dx, uint256 min_dy, bool use_eth ) external payable; function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); } // Part: ICurveV2Pool interface ICurveV2Pool { function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); function exchange_underlying( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external payable returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external returns (uint256); function future_A_gamma_time() external view returns (uint256); function lp_price() external view returns (uint256); } // Part: IMerkleDistributorV2 interface IMerkleDistributorV2 { enum Option { Claim, ClaimAsETH, ClaimAsCRV, ClaimAsCVX, ClaimAndStake } function vault() external view returns (address); function merkleRoot() external view returns (bytes32); function week() external view returns (uint32); function frozen() external view returns (bool); function isClaimed(uint256 index) external view returns (bool); function setApprovals() external; function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; function claimAs( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, Option option ) external; function claimAs( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, Option option, uint256 minAmountOut ) external; function freeze() external; function unfreeze() external; function stake() external; function updateMerkleRoot(bytes32 newMerkleRoot, bool unfreeze) external; function updateDepositor(address newDepositor) external; function updateAdmin(address newAdmin) external; function updateVault(address newVault) external; event Claimed( uint256 index, uint256 amount, address indexed account, uint256 indexed week, Option option ); event DepositorUpdated( address indexed oldDepositor, address indexed newDepositor ); event AdminUpdated(address indexed oldAdmin, address indexed newAdmin); event VaultUpdated(address indexed oldVault, address indexed newVault); event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week); } // Part: IRewards interface IRewards { function balanceOf(address) external view returns (uint256); function stake(address, uint256) external; function stakeFor(address, uint256) external; function withdraw(address, uint256) external; function exit(address) external; function getReward(address) external; function queueNewRewards(uint256) external; function notifyRewardAmount(uint256) external; function addExtraReward(address) external; function stakingToken() external view returns (address); function rewardToken() external view returns (address); function earned(address account) external view returns (uint256); } // Part: ITriPool interface ITriPool { function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function get_virtual_price() external view returns (uint256); } // Part: IUniV2Router interface IUniV2Router { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: IUnionVault interface IUnionVault { enum Option { Claim, ClaimAsETH, ClaimAsCRV, ClaimAsCVX, ClaimAndStake } function withdraw(address _to, uint256 _shares) external returns (uint256 withdrawn); function withdrawAll(address _to) external returns (uint256 withdrawn); function withdrawAs( address _to, uint256 _shares, Option option ) external; function withdrawAs( address _to, uint256 _shares, Option option, uint256 minAmountOut ) external; function withdrawAllAs(address _to, Option option) external; function withdrawAllAs( address _to, Option option, uint256 minAmountOut ) external; function depositAll(address _to) external returns (uint256 _shares); function deposit(address _to, uint256 _amount) external returns (uint256 _shares); function harvest() external; function balanceOfUnderlying(address user) external view returns (uint256 amount); function outstanding3CrvRewards() external view returns (uint256 total); function outstandingCvxRewards() external view returns (uint256 total); function outstandingCrvRewards() external view returns (uint256 total); function totalUnderlying() external view returns (uint256 total); function underlying() external view returns (address); function setPlatform(address _platform) external; function setPlatformFee(uint256 _fee) external; function setCallIncentive(uint256 _incentive) external; function setWithdrawalPenalty(uint256 _penalty) external; function setApprovals() external; } // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Ownable /** * @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; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: UnionBase // Common variables and functions contract UnionBase { address public constant CVXCRV_STAKING_CONTRACT = 0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e; address public constant CURVE_CRV_ETH_POOL = 0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511; address public constant CURVE_CVX_ETH_POOL = 0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4; address public constant CURVE_CVXCRV_CRV_POOL = 0x9D0464996170c6B9e75eED71c68B99dDEDf279e8; address public constant CRV_TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant CVXCRV_TOKEN = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; address public constant CVX_TOKEN = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; uint256 public constant CRVETH_ETH_INDEX = 0; uint256 public constant CRVETH_CRV_INDEX = 1; int128 public constant CVXCRV_CRV_INDEX = 0; int128 public constant CVXCRV_CVXCRV_INDEX = 1; uint256 public constant CVXETH_ETH_INDEX = 0; uint256 public constant CVXETH_CVX_INDEX = 1; IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT); ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL); ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL); ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL); /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv(uint256 amount, address recipient) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, 0); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, minAmountOut); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _crvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CRV_INDEX, CVXCRV_CVXCRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv(uint256 amount, address recipient) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, 0); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, minAmountOut); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _cvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CVXCRV_INDEX, CVXCRV_CRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount) internal returns (uint256) { return _crvToEth(amount, 0); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _crvToEth(amount, minAmountOut); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _crvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: 0}( CRVETH_CRV_INDEX, CRVETH_ETH_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount) internal returns (uint256) { return _ethToCrv(amount, 0); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCrv(amount, minAmountOut); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: amount}( CRVETH_ETH_INDEX, CRVETH_CRV_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount) internal returns (uint256) { return _ethToCvx(amount, 0); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCvx(amount, minAmountOut); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return cvxEthSwap.exchange_underlying{value: amount}( CVXETH_ETH_INDEX, CVXETH_CVX_INDEX, amount, minAmountOut ); } modifier notToZeroAddress(address _to) { require(_to != address(0), "Invalid address!"); _; } } // File: ExtraZaps.sol contract ExtraZaps is Ownable, UnionBase { using SafeERC20 for IERC20; address public immutable vault; address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address private constant TRICRYPTO = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46; address private constant TRIPOOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address private constant TRICRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address private constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address private constant CONVEX_TRIPOOL_TOKEN = 0x30D9410ED1D5DA1F6C8391af5338C93ab8d4035C; address private constant CONVEX_TRIPOOL_REWARDS = 0x689440f2Ff927E1f24c72F1087E1FAF471eCe1c8; address private constant CONVEX_LOCKER = 0x72a19342e8F1838460eBFCCEf09F6585e32db86E; ICurveTriCrypto triCryptoSwap = ICurveTriCrypto(TRICRYPTO); ITriPool triPool = ITriPool(TRIPOOL); IBooster booster = IBooster(BOOSTER); IRewards triPoolRewards = IRewards(CONVEX_TRIPOOL_REWARDS); ICVXLocker locker = ICVXLocker(CONVEX_LOCKER); IMerkleDistributorV2 distributor; constructor(address _vault, address _distributor) { vault = _vault; distributor = IMerkleDistributorV2(_distributor); } function setApprovals() external { IERC20(TRICRV).safeApprove(BOOSTER, 0); IERC20(TRICRV).safeApprove(BOOSTER, type(uint256).max); IERC20(USDT).safeApprove(TRIPOOL, 0); IERC20(USDT).safeApprove(TRIPOOL, type(uint256).max); IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove(CONVEX_TRIPOOL_REWARDS, 0); IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove( CONVEX_TRIPOOL_REWARDS, type(uint256).max ); IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0); IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, type(uint256).max); IERC20(CVXCRV_TOKEN).safeApprove(vault, 0); IERC20(CVXCRV_TOKEN).safeApprove(vault, type(uint256).max); IERC20(CVX).safeApprove(CONVEX_LOCKER, 0); IERC20(CVX).safeApprove(CONVEX_LOCKER, type(uint256).max); } /// @notice Retrieves user's uCRV and unstake to ETH /// @param amount - the amount of uCRV to unstake function _withdrawFromVaultAsEth(uint256 amount) internal { IERC20(vault).safeTransferFrom(msg.sender, address(this), amount); IUnionVault(vault).withdrawAllAs( address(this), IUnionVault.Option.ClaimAsETH ); } /// @notice swap ETH to USDT via Curve's tricrypto /// @param amount - the amount of ETH to swap /// @param minAmountOut - the minimum amount expected function _swapEthToUsdt( uint256 amount, uint256 minAmountOut, address to ) internal { triCryptoSwap.exchange{value: amount}( 2, // ETH 0, // USDT amount, minAmountOut, true ); } /// @notice Unstake from the Pounder to USDT /// @param amount - the amount of uCRV to unstake /// @param minAmountOut - the min expected amount of USDT to receive /// @param to - the adress that will receive the USDT /// @return amount of USDT obtained function claimFromVaultAsUsdt( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) returns (uint256) { _withdrawFromVaultAsEth(amount); _swapEthToUsdt(address(this).balance, minAmountOut, to); uint256 _usdtAmount = IERC20(USDT).balanceOf(address(this)); if (to != address(this)) { IERC20(USDT).safeTransfer(to, _usdtAmount); } return _usdtAmount; } /// @notice Claim from the distributor, unstake and returns USDT. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - the min expected amount of USDT to receive /// @param to - the adress that will receive the USDT /// @return amount of USDT obtained function claimFromDistributorAsUsdt( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) returns (uint256) { distributor.claim(index, account, amount, merkleProof); return claimFromVaultAsUsdt(amount, minAmountOut, to); } /// @notice Unstake from the Pounder to stables and stake on 3pool convex for yield /// @param amount - amount of uCRV to unstake /// @param minAmountOut - minimum amount of 3CRV (NOT USDT!) /// @param to - address on behalf of which to stake function claimFromVaultAndStakeIn3PoolConvex( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) { // claim as USDT uint256 _usdtAmount = claimFromVaultAsUsdt(amount, 0, address(this)); // add USDT to Tripool triPool.add_liquidity([0, 0, _usdtAmount], minAmountOut); // deposit on Convex booster.depositAll(9, false); // stake on behalf of user triPoolRewards.stakeFor( to, IERC20(CONVEX_TRIPOOL_TOKEN).balanceOf(address(this)) ); } /// @notice Claim from the distributor, unstake and deposits in 3pool. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - minimum amount of 3CRV (NOT USDT!) /// @param to - address on behalf of which to stake function claimFromDistributorAndStakeIn3PoolConvex( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultAndStakeIn3PoolConvex(amount, minAmountOut, to); } /// @notice Claim to any token via a univ2 router /// @notice Use at your own risk /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of output token expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param outputToken - address of the token to swap to /// @param to - address of the final recipient of the swapped tokens function claimFromVaultViaUniV2EthPair( uint256 amount, uint256 minAmountOut, address router, address outputToken, address to ) public notToZeroAddress(to) { require(router != address(0)); _withdrawFromVaultAsEth(amount); address[] memory _path = new address[](2); _path[0] = WETH; _path[1] = outputToken; IUniV2Router(router).swapExactETHForTokens{ value: address(this).balance }(minAmountOut, _path, to, block.timestamp + 60); } /// @notice Claim to any token via a univ2 router /// @notice Use at your own risk /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of output token expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param outputToken - address of the token to swap to /// @param to - address of the final recipient of the swapped tokens function claimFromDistributorViaUniV2EthPair( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address router, address outputToken, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultViaUniV2EthPair( amount, minAmountOut, router, outputToken, to ); } /// @notice Unstake from the Pounder as CVX and locks it /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of CVX expected /// @param to - address to lock on behalf of function claimFromVaultAsCvxAndLock( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) { IERC20(vault).safeTransferFrom(msg.sender, address(this), amount); IUnionVault(vault).withdrawAllAs( address(this), IUnionVault.Option.ClaimAsCVX, minAmountOut ); locker.lock(to, IERC20(CVX).balanceOf(address(this)), 0); } /// @notice Claim from the distributor, unstake to CVX and lock. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - min amount of CVX expected /// @param to - address to lock on behalf of function claimFromDistributorAsCvxAndLock( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultAsCvxAndLock(amount, minAmountOut, to); } /// @notice Deposit into the pounder from ETH /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function depositFromEth(uint256 minAmountOut, address to) external payable notToZeroAddress(to) { require(msg.value > 0, "cheap"); _depositFromEth(msg.value, minAmountOut, to); } /// @notice Internal function to deposit ETH to the pounder /// @param amount - amount of ETH /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function _depositFromEth( uint256 amount, uint256 minAmountOut, address to ) internal { uint256 _crvAmount = _swapEthToCrv(amount); uint256 _cvxCrvAmount = _swapCrvToCvxCrv( _crvAmount, address(this), minAmountOut ); IUnionVault(vault).deposit(to, _cvxCrvAmount); } /// @notice Deposit into the pounder from CRV /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function depositFromCrv( uint256 amount, uint256 minAmountOut, address to ) external notToZeroAddress(to) { IERC20(CRV_TOKEN).safeTransferFrom(msg.sender, address(this), amount); uint256 _cvxCrvAmount = _swapCrvToCvxCrv( amount, address(this), minAmountOut ); IUnionVault(vault).deposit(to, _cvxCrvAmount); } /// @notice Deposit into the pounder from any token via Uni interface /// @notice Use at your own risk /// @dev Zap contract needs approval for spending of inputToken /// @param amount - min amount of input token /// @param minAmountOut - min amount of cvxCRV expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param inputToken - address of the token to swap from, needs to have an ETH pair on router used /// @param to - address to stake on behalf of function depositViaUniV2EthPair( uint256 amount, uint256 minAmountOut, address router, address inputToken, address to ) external notToZeroAddress(to) { require(router != address(0)); IERC20(inputToken).safeTransferFrom(msg.sender, address(this), amount); address[] memory _path = new address[](2); _path[0] = inputToken; _path[1] = WETH; IERC20(inputToken).safeApprove(router, 0); IERC20(inputToken).safeApprove(router, amount); IUniV2Router(router).swapExactTokensForETH( amount, 1, _path, address(this), block.timestamp + 1 ); _depositFromEth(address(this).balance, minAmountOut, to); } /// @notice Execute calls on behalf of contract /// (for instance to retrieve locked tokens) function execute( address _to, uint256 _value, bytes calldata _data ) external onlyOwner returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value: _value}(_data); return (success, result); } receive() external payable {} }
@notice Unstake from the Pounder as CVX and locks it @param amount - amount of uCRV to unstake @param minAmountOut - min amount of CVX expected @param to - address to lock on behalf of
function claimFromVaultAsCvxAndLock( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) { IERC20(vault).safeTransferFrom(msg.sender, address(this), amount); IUnionVault(vault).withdrawAllAs( address(this), IUnionVault.Option.ClaimAsCVX, minAmountOut ); locker.lock(to, IERC20(CVX).balanceOf(address(this)), 0); }
75,345
[ 1, 984, 334, 911, 628, 326, 453, 465, 765, 487, 385, 58, 60, 471, 13046, 518, 225, 3844, 300, 3844, 434, 582, 5093, 58, 358, 640, 334, 911, 225, 1131, 6275, 1182, 300, 1131, 3844, 434, 385, 58, 60, 2665, 225, 358, 300, 1758, 358, 2176, 603, 12433, 6186, 434, 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, 7516, 1265, 12003, 1463, 39, 26982, 1876, 2531, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 1131, 6275, 1182, 16, 203, 3639, 1758, 358, 203, 565, 262, 1071, 486, 774, 7170, 1887, 12, 869, 13, 288, 203, 3639, 467, 654, 39, 3462, 12, 26983, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 467, 14325, 12003, 12, 26983, 2934, 1918, 9446, 1595, 1463, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 467, 14325, 12003, 18, 1895, 18, 9762, 1463, 22007, 60, 16, 203, 5411, 1131, 6275, 1182, 203, 3639, 11272, 203, 3639, 28152, 18, 739, 12, 869, 16, 467, 654, 39, 3462, 12, 22007, 60, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 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 ]
./full_match/43114/0x02E07B6F27E5eC37CA6E9f846b6D48704031625A/sources/CauldronV2Multichain.sol
@title Cauldron @dev This contract allows contract calls to any contract (except BentoBox) from arbitrary callers thus, don't trust calls from this contract in any circumstances. Immutables (for MasterContract and all clones) MasterContract variables Per clone variables Clone init settings Total amounts User balances
contract CauldronV2Multichain is BoringOwnable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; using RebaseLibrary for Rebase; using BoringERC20 for IERC20; event LogExchangeRate(uint256 rate); event LogAccrue(uint128 accruedAmount); event LogAddCollateral(address indexed from, address indexed to, uint256 share); event LogRemoveCollateral(address indexed from, address indexed to, uint256 share); event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part); event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part); event LogFeeTo(address indexed newFeeTo); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); IBentoBoxV1 public immutable bentoBox; CauldronV2Multichain public immutable masterContract; IERC20 public immutable magicInternetMoney; address public feeTo; IERC20 public collateral; IOracle public oracle; bytes public oracleData; mapping(address => uint256) public userCollateralShare; mapping(address => uint256) public userBorrowPart; uint256 public exchangeRate; } struct AccrueInfo { uint64 lastAccrued; uint128 feesEarned; uint64 INTEREST_PER_SECOND; } AccrueInfo public accrueInfo; uint256 private constant EXCHANGE_RATE_PRECISION = 1e18; uint256 public LIQUIDATION_MULTIPLIER; uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5; uint256 public BORROW_OPENING_FEE; uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5; uint256 private constant DISTRIBUTION_PART = 10; uint256 private constant DISTRIBUTION_PRECISION = 100; uint256 public COLLATERIZATION_RATE; constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public { bentoBox = bentoBox_; magicInternetMoney = magicInternetMoney_; masterContract = this; } function init(bytes calldata data) public payable override { require(address(collateral) == address(0), "Cauldron: already initialized"); (collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256)); require(address(collateral) != address(0), "Cauldron: bad pair"); } function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128(); function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) { uint256 borrowPart = userBorrowPart[user]; if (borrowPart == 0) return true; uint256 collateralShare = userCollateralShare[user]; if (collateralShare == 0) return false; Rebase memory _totalBorrow = totalBorrow; return bentoBox.toAmount( collateral, collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE), false ) >= borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } modifier solvent() { _; require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); rate = exchangeRate; } } function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); rate = exchangeRate; } } } else { function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much"); bentoBox.transfer(token, msg.sender, address(this), share); } } function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much"); bentoBox.transfer(token, msg.sender, address(this), share); } } } else { function addCollateral( address to, bool skim, uint256 share ) public { userCollateralShare[to] = userCollateralShare[to].add(share); uint256 oldTotalCollateralShare = totalCollateralShare; totalCollateralShare = oldTotalCollateralShare.add(share); _addTokens(collateral, share, oldTotalCollateralShare, skim); emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share); } function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); bentoBox.transfer(collateral, address(this), to, share); } function removeCollateral(address to, uint256 share) public solvent { accrue(); _removeCollateral(to, share); } function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part); share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); } function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } function _repay( address to, bool skim, uint256 part ) internal returns (uint256 amount) { (totalBorrow, amount) = totalBorrow.sub(part, true); userBorrowPart[to] = userBorrowPart[to].sub(part); uint256 share = bentoBox.toShare(magicInternetMoney, amount, true); bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share); emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part); } function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } uint8 internal constant ACTION_REMOVE_COLLATERAL = 4; uint8 internal constant ACTION_BORROW = 5; uint8 internal constant ACTION_GET_REPAY_SHARE = 6; uint8 internal constant ACTION_GET_REPAY_PART = 7; uint8 internal constant ACTION_ACCRUE = 8; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; uint8 internal constant ACTION_BENTO_WITHDRAW = 21; uint8 internal constant ACTION_BENTO_TRANSFER = 22; uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23; uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; uint8 internal constant ACTION_REPAY = 2; uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_BENTO_DEPOSIT = 20; uint8 internal constant ACTION_CALL = 30; function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); share = int256(_num(share, value1, value2)); } return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share)); function _bentoWithdraw( bytes memory data, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2)); } function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); callData = abi.encodePacked(callData, value2); callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); require(success, "Cauldron: call failed"); return (returnData, returnValues); } function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); callData = abi.encodePacked(callData, value2); callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); require(success, "Cauldron: call failed"); return (returnData, returnValues); } } else if (!useValue1 && useValue2) { } else if (useValue1 && useValue2) { (bool success, bytes memory returnData) = callee.call{value: value}(callData); struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } } else if (action == ACTION_REPAY) { } else if (action == ACTION_REMOVE_COLLATERAL) { } else if (action == ACTION_BORROW) { } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { } else if (action == ACTION_BENTO_SETAPPROVAL) { } else if (action == ACTION_BENTO_DEPOSIT) { } else if (action == ACTION_BENTO_WITHDRAW) { } else if (action == ACTION_BENTO_TRANSFER) { } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { } else if (action == ACTION_CALL) { function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } } else if (returnValues == 2) { } else if (action == ACTION_GET_REPAY_SHARE) { } else if (action == ACTION_GET_REPAY_PART) { function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); (value1, value2) = _bentoWithdraw(datas[i], value1, value2); (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); (value1, value2) = abi.decode(returnData, (uint256, uint256)); } int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } allCollateralShare = allCollateralShare.add(collateralShare); function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } bentoBox.transfer(collateral, address(this), to, allCollateralShare); function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); { allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); uint256 _feesEarned = accrueInfo.feesEarned; uint256 share = bentoBox.toShare(magicInternetMoney, _feesEarned, false); bentoBox.transfer(magicInternetMoney, address(this), _feeTo, share); accrueInfo.feesEarned = 0; emit LogWithdrawFees(_feeTo, _feesEarned); } function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } function reduceSupply(uint256 amount) public { require(msg.sender == masterContract.owner(), "Caller is not the owner"); bentoBox.withdraw(magicInternetMoney, address(this), masterContract.owner(), amount, 0); } }
4,631,454
[ 1, 23508, 332, 72, 1949, 225, 1220, 6835, 5360, 6835, 4097, 358, 1281, 6835, 261, 14137, 605, 29565, 3514, 13, 628, 11078, 19932, 12493, 16, 2727, 1404, 10267, 4097, 628, 333, 6835, 316, 1281, 29951, 2639, 18, 2221, 10735, 1538, 261, 1884, 13453, 8924, 471, 777, 927, 5322, 13, 13453, 8924, 3152, 5722, 3236, 3152, 12758, 1208, 1947, 10710, 30980, 2177, 324, 26488, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 23318, 332, 72, 1949, 58, 22, 5049, 1354, 530, 353, 605, 6053, 5460, 429, 16, 6246, 2440, 8924, 288, 203, 565, 1450, 605, 6053, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 605, 6053, 10477, 10392, 364, 2254, 10392, 31, 203, 565, 1450, 868, 1969, 9313, 364, 868, 1969, 31, 203, 565, 1450, 605, 6053, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 871, 1827, 11688, 4727, 12, 11890, 5034, 4993, 1769, 203, 565, 871, 1827, 8973, 86, 344, 12, 11890, 10392, 4078, 86, 5957, 6275, 1769, 203, 565, 871, 1827, 986, 13535, 2045, 287, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 7433, 1769, 203, 565, 871, 1827, 3288, 13535, 2045, 287, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 7433, 1769, 203, 565, 871, 1827, 38, 15318, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 3844, 16, 2254, 5034, 1087, 1769, 203, 565, 871, 1827, 426, 10239, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 3844, 16, 2254, 5034, 1087, 1769, 203, 565, 871, 1827, 14667, 774, 12, 2867, 8808, 394, 14667, 774, 1769, 203, 565, 871, 1827, 1190, 9446, 2954, 281, 12, 2867, 8808, 14036, 774, 16, 2254, 5034, 1656, 281, 41, 1303, 329, 13724, 1769, 203, 203, 565, 23450, 29565, 3514, 58, 21, 1071, 11732, 324, 29565, 3514, 31, 203, 565, 23318, 332, 72, 1949, 58, 22, 5049, 1354, 530, 1071, 11732, 4171, 8924, 31, 203, 565, 467, 654, 39, 3462, 1071, 11732, 2 ]
./partial_match/1/0x47B0f414d5298CFFF5E043767d6715E2a5D92CC6/sources/BoiChillClub.sol
* @dev Sets the primary sale recipient address. @param recipient_ The address of the primary sale recipient./
function setupPrimarySaleRecipient(address recipient_) external override onlyOwner { _setupPrimarySaleRecipient(recipient_); }
4,455,952
[ 1, 2785, 326, 3354, 272, 5349, 8027, 1758, 18, 225, 8027, 67, 1021, 1758, 434, 326, 3354, 272, 5349, 8027, 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 ]
[ 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, 3875, 6793, 30746, 18241, 12, 2867, 8027, 67, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 389, 8401, 6793, 30746, 18241, 12, 20367, 67, 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 ]
./full_match/5/0x0B7082697a7bb855fb6F7Bf052B94464D98aa57E/sources/extension/TransactionFee.sol
@dev Platform wallet address @dev Transaction cost @dev At any given moment, returns the transaction fee.
function getTransactionFee() public view returns (uint256) { return transactionFee; }
1,958,086
[ 1, 8201, 9230, 1758, 225, 5947, 6991, 225, 2380, 1281, 864, 10382, 16, 1135, 326, 2492, 14036, 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 ]
[ 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, 15674, 14667, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2492, 14667, 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, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/GSN/Context.sol"; /*************** POLL CONTRACT ***************/ contract PollingStation { using SafeMath for uint256; //GLOBAL CONSTANTS uint256 public periodDuration; // set length of period for a poll (1 = 1 second) uint256 public pollLength; // set length of the poll in periods uint256 public startTime; // set start time for poll uint256 public creationTime; // needed to determine the current period address public pollster; // creator of the poll address public voteToken; // token used to decide voting weight string public pollingStationName; // HARD-CODED LIMITS // Set arbitrarily because of gas limits...you know uint256 constant MAX_VOTERS = 1000; // maximum number of voters uint256 constant MAX_OPTIONS = 20; // maximum number of options //EVENTS event PeepsPollingCreated(address pollster, address voteToken, uint256 periodDuration); event RegisterVoters(address[] newVoters, uint256[] voterTokens); event CreateBallot(uint256 proposalIndex, uint256 startingPeriod, uint256 pollLength, bytes32[] options, string details); event SubmitVote(uint256 proposalIndex, address voter, string option, uint256 tokensSpent, uint256 quadraticVotes); event TabulateBallot(uint256 ballotIndex, string winningOption); event Abort(uint256 ballotIndex); event UpdateDelegateKey(address sender, address newDelegateKey); //This is a type for a voter. struct Voter { address delegate; // allows for user to delegate vote to a different personal wallet address uint256 tokenBalance; // index of the voted proposal uint256 highestIndexVote; // highest ballot index # on which the voter voted uint256 penaltyBox; // set to the period in which the voter is placed in the penalty box bool exists; // always true once a voter has been created } struct userBallot { address owner; uint256[] votes; uint256[] quadraticVotes; bytes32[] options; } // @Dev in v2 call this an "Election" struct Ballot { bytes32[] options; // list of options to include in a ballot uint256[] totalVotes; // total votes each candidate received uint256[] totalQuadraticVotes; // calculation of quadratic votes for each candidate uint256 startingPeriod; // the period in which voting can start for this proposal uint256 pollLength; // the period when the proposal closes bytes32 winningOption; // name of winning option bool tabulated; // true only if the proposal has been processed bool aborted; // true only if applicant calls "abort" fn before end of voting period string details; // proposal details - could be IPFS hash, plaintext, or JSON mapping (address => userBallot) votesByVoter; // list of options and corresponding votes } //MODIFIERS modifier onlyPollster() { require(msg.sender == pollster, "Error: only the pollster can take this action"); _; } // stores a `Voter` struct for each voter address. mapping(address => Voter) public voters; mapping(address => address) public voterAddressByDelegateKey; // mapping of proposals for proposalId mapping(uint256 => Ballot) public ballots; Ballot[] public ballotQueue; constructor( address _pollster, address _voteToken, uint256 _periodDuration, string memory _pollingStationName ) public { voteToken = _voteToken; pollster = _pollster; voteToken = _voteToken; periodDuration = _periodDuration; pollingStationName = _pollingStationName; creationTime = now; emit PeepsPollingCreated(_pollster, _voteToken, _periodDuration); } /*************** VOTER REGISTRATION ***************/ // registers new voters, set voterTokens to 0 if you don't want to mint new tokens for that voter function registerVoters(address[] memory newVoters, uint256[] memory voterTokens) external onlyPollster { require(newVoters.length == voterTokens.length, "your arrays do not match in length"); for (uint256 i = 0; i < newVoters.length; i++) { _registerVoter(newVoters[i], voterTokens[i]); } emit RegisterVoters(newVoters, voterTokens); } function _registerVoter(address newVoter, uint256 voterTokens) internal { // if new voter is already taken by a voters's delegateKey, reset it to their voter address if (voters[voterAddressByDelegateKey[newVoter]].exists == true) { address voterToOverride = voterAddressByDelegateKey[newVoter]; voterAddressByDelegateKey[voterToOverride] = voterToOverride; voters[voterToOverride].delegate = voterToOverride; } uint256 allocatedTokens = voterTokens; if (voterTokens > 0) { require(IERC20(voteToken).approve(address(this), voterTokens), "approval failed"); require(IERC20(voteToken).transferFrom(address(this), newVoter, allocatedTokens), "token transfer failed"); } voters[newVoter] = Voter({ delegate: newVoter,// allows for user to delegate vote to a different personal wallet address tokenBalance: 0, // index of the voted proposal highestIndexVote: 0, // highest ballot index # on which the voter voted penaltyBox: 0, // set to the period in which the voter is placed in the penalty box exists: true // always true once a voter has been created }); voterAddressByDelegateKey[newVoter] = newVoter; uint256 initialTokenBalance = getVoterTokenBalance(newVoter); voters[newVoter].tokenBalance = initialTokenBalance; } /***************** BALLOT FUNCTIONS *****************/ function createBallot( bytes32[] memory options, uint256 _startingPeriod, uint256 _pollLength, string memory details ) public onlyPollster { require(options.length > 0, "Need to have at least 1 option."); require(options.length < MAX_OPTIONS); for (uint i=0; i < options.length; i++) { require(options[i] != 0, "Option cannot be blank"); } require(_startingPeriod > getCurrentPeriod().add(1), "must set starting period in future"); // create new ballot for some votes ... /* bytes32[] options; // list of options to include in a ballot uint256[] totalVotes; // total votes each candidate received uint256[] totalQuadraticVotes; // calculation of quadratic votes for each candidate uint256 startingPeriod; // the period in which voting can start for this proposal uint256 pollLength; // the period when the proposal closes string winningOption; // name of winning option bool tabulated; // true only if the proposal has been processed bool aborted; // true only if applicant calls "abort" fn before end of voting period string details; // proposal details - could be IPFS hash, plaintext, or JSON mapping (address => userBallot) votesByVoter; // list of options and corresponding votes */ Ballot memory ballot = Ballot({ options: options, totalVotes: new uint256[](options.length), totalQuadraticVotes: new uint256[](options.length), startingPeriod: _startingPeriod, pollLength: _pollLength, winningOption: 0, tabulated: false, aborted: false, details: details }); // ... and append it to the queue ballotQueue.push(ballot); uint256 ballotIndex = ballotQueue.length.sub(1); emit CreateBallot(ballotIndex, _startingPeriod, _pollLength, options, details); } function submitVote(uint256 ballotIndex, bytes32 option, uint256 votes) public { require(voters[voterAddressByDelegateKey[msg.sender]].exists = true, "not a voter"); address voterAddress = voterAddressByDelegateKey[msg.sender]; Voter storage voter = voters[voterAddress]; require(ballotIndex < ballotQueue.length, "Ballot does not exist"); Ballot storage ballot = ballotQueue[ballotIndex]; require(votes > 0, "At least one vote must be cast"); require(getCurrentPeriod() >= ballot.startingPeriod, "Voting period has not started"); require(!hasVotingPeriodExpired(ballotIndex), "Voting period has expired"); require(!ballot.aborted, "Ballot has been aborted"); userBallot storage voterBallot = ballot.votesByVoter[voterAddress]; // store vote uint256 totalVotes; uint256 newVotes; uint256 quadraticVotes; //Set empty array for new ballot if (voterBallot.votes.length == 0) { voterBallot.votes = new uint256[](ballot.options.length); voterBallot.quadraticVotes = new uint256[](ballot.options.length); voterBallot.options = new bytes32[](ballot.options.length); } for (uint i = 0; i < ballot.options.length; i++) { if (ballot.options[i] == option) { newVotes = voterBallot.votes[i].add(votes); uint256 prevquadraticVotes = voterBallot.quadraticVotes[i]; quadraticVotes = sqrt(newVotes); ballot.totalVotes[i] = ballot.totalVotes[i].add(votes); ballot.totalQuadraticVotes[i] = ballot.totalQuadraticVotes[i].sub(prevquadraticVotes).add(quadraticVotes); voterBallot.options[i] = option; voterBallot.votes[i] = newVotes; voterBallot.quadraticVotes[i] = quadraticVotes; if (ballotIndex > voter.highestIndexVote) { voter.highestIndexVote = ballotIndex; } } totalVotes = totalVotes.add(voterBallot.votes[i]); } require(totalVotes <= voter.tokenBalance, "Not enough tokens to cast this quantity of votes"); require(IERC20(voteToken).transfer(address(this), votes), "vote token transfer failed"); emit SubmitVote(ballotIndex, msg.sender, voterAddress, option, votes, quadraticVotes); } function tabulateBallot(uint256 ballotIndex) public onlyPollster { require(ballotIndex < ballotQueue.length, "Ballot does not exist"); Ballot storage ballot = ballotQueue[ballotIndex]; require(getCurrentPeriod() >= ballot.startingPeriod.add(ballot.pollLength), "Voting has not ended is not ready to be processed"); require(ballot.tabulated == false, "Ballot has already been tabulated"); require(ballotIndex == 0 || ballotQueue[ballotIndex.sub(1)].tabulated, "Previous ballot must be tabulated first"); // Get favorite option uint256 largest = 0; uint chosen = 0; require(ballot.totalVotes.length > 0, "This ballot has not received any votes."); bool didPass = true; for (uint i = 0; i < ballot.totalVotes.length; i++) { require(ballot.totalQuadraticVotes[i] != largest, "This ballot has no winner" ); if (ballot.totalQuadraticVotes[i] > largest) { largest = ballot.totalQuadraticVotes[i]; chosen = i; } bytes32 winningOption = ballot.options[i]; if (!ballot.aborted) { ballot.winningOption = winningOption; } } bytes32 winningOption = ballot.winningOption; ballot.tabulated = true; emit TabulateBallot(ballotIndex, winningOption); } function abort(uint256 ballotIndex) public onlyPollster { require(ballotIndex < ballotQueue.length, "Moloch::abort - proposal does not exist"); Ballot storage ballot = ballotQueue[ballotIndex]; require(getCurrentPeriod() < ballot.startingPeriod, "Voting period cannot have started"); require(!ballot.aborted, "Ballot must not have already been aborted"); ballot.aborted = true; emit Abort(ballotIndex); } /*************** VOTER HELPER FUNCTIONS ***************/ function getVoterTokenBalance(address voter) public view returns (uint256) { require(voters[voter].exists == true, "voter does not exist yet"); require(IERC20(voteToken).balanceOf(voter) > 0, "no token balance"); return IERC20(voteToken).balanceOf(voter); } function updateVoterTokenBalance(address voter) internal returns (uint256) { require(voters[msg.sender].exists == true, "no voter on record"); voters[voter].tokenBalance == IERC20(voteToken).balanceOf(voter); } function updateDelegateKey(address newDelegateKey) external { require(voters[msg.sender].tokenBalance > 0, "not a current voter"); require(newDelegateKey != address(0), "newDelegateKey zeroed"); // skip checks if voter is setting the delegate key to their voter address if (newDelegateKey != msg.sender) { require(voters[newDelegateKey].exists == false, "cannot overwrite voters"); require(voters[voterAddressByDelegateKey[newDelegateKey]].exists == false, "cannot overwrite keys"); } Voter storage voter = voters[msg.sender]; voterAddressByDelegateKey[voter.delegate] = address(0); voterAddressByDelegateKey[newDelegateKey] = msg.sender; voter.delegate = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } function getCurrentPeriod() public view returns (uint256) { return now.sub(creationTime).div(periodDuration); } function hasVotingPeriodExpired(uint256 ballotIndex) public view returns (bool) { Ballot storage ballot = ballotQueue[ballotIndex]; return getCurrentPeriod() >= ballot.startingPeriod + ballot.pollLength; } 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; } } } /*************** POLL FACTORY ***************/ contract PeepsPollFactory { // Built by Peeps Democracy for fun ~ Use at own risk! uint8 public version = 1; // factory settings uint256 public pollTax; address payable public peepsWallet; //events event NewPollingStation(address PollingStation, address pollster, address voteToken); constructor ( uint256 _pollTax, address payable _peepsWallet) public { pollTax = _pollTax; peepsWallet = _peepsWallet; } function newPollingStation( address _pollster, address _voteToken, uint256 _periodDuration, string memory _pollingStationName) payable public { PollingStation = new PollingStation( _pollster, _voteToken, _periodDuration, _pollingStationName); address(peepsWallet).transfer(msg.value); emit NewPollingStation(address(PollingStation), _pollster, _voteToken); } }
highest ballot index # on which the voter voted
uint256 highestIndexVote;
5,517,499
[ 1, 8766, 395, 26503, 352, 770, 225, 603, 1492, 326, 331, 20005, 331, 16474, 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, 3639, 2254, 5034, 9742, 1016, 19338, 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 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // 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/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/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/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/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/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/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/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/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: contracts/Symbio.sol pragma solidity ^0.8.11; contract Symbio is ERC721, Ownable { string _baseTokenURI = "https://metadata.symbio.gg/"; struct Symbiote { // General records uint256 tier; uint256 total_staked; uint256 stake_started_at; uint256 rewards_claimed_at; uint256 total_rewards_unclaimed; uint256 total_rewards_claimed; } Symbiote[] public symbiotes; // Total supply uint256 public totalSupply; // Total supply by tier uint256[6] public totalSupplyByTier; // Max supply uint256 public maxSupply = 19998; // max supply by tier uint256[6] public maxSupplyByTier = [3333, 3333, 3333, 3333, 3333, 3333]; // actual phase uint256 private actualPhase = 0; // max supply by tier on phase uint256[6][10] public maxSupplyByTierOnPhase; // phase => tier => max // Whitelist mapping(address => uint) public whitelist; // Whitelist Sale Time uint256[2] public whitelistSaleTime; // Only Owners Sale Time uint256[2] public ownerSaleTime; // Public Sale Time uint256[2] public publicSaleTime; // value of usd token to mint by tier uint[6] public mintValueByTier = [0.05 ether, 0.10 ether, 0.20 ether, 1.00 ether, 2.00 ether, 10.00 ether]; // Maximum of Mint Per Tx uint256 public maxMintsPerTx = 3; // Yield multiply by 10000 uint256 public yield = 110; constructor() ERC721("Symbio", "SYMBIO"){ // First symbiote index 0 symbiotes.push(Symbiote(0, 0, 0, 0, 0, 0)); maxSupplyByTierOnPhase[0] = [ 33, 13, 3, 0, 0, 0]; maxSupplyByTierOnPhase[1] = [ 333, 33, 13, 3, 0, 0]; maxSupplyByTierOnPhase[2] = [1333, 333, 33, 13, 3, 0]; maxSupplyByTierOnPhase[3] = [2333, 1333, 333, 33, 13, 3]; maxSupplyByTierOnPhase[4] = [3333, 2333, 1333, 333, 33, 13]; maxSupplyByTierOnPhase[5] = [3333, 3333, 2333, 1333, 333, 33]; maxSupplyByTierOnPhase[6] = [3333, 3333, 3333, 2333, 1333, 333]; maxSupplyByTierOnPhase[7] = [3333, 3333, 3333, 3333, 2333, 1333]; maxSupplyByTierOnPhase[8] = [3333, 3333, 3333, 3333, 3333, 2333]; maxSupplyByTierOnPhase[9] = [3333, 3333, 3333, 3333, 3333, 3333]; } function publicSale(uint _tier, uint256 _amount) public payable{ require(publicSaleTime[0] <= block.timestamp && publicSaleTime[1] > block.timestamp, "Public sale not started!"); mint(_tier, _amount); } function ownerSale(uint _tier, uint256 _amount) public payable{ require(ownerSaleTime[0] <= block.timestamp && ownerSaleTime[1] > block.timestamp, "Owner sale not started!"); require(balanceOf(msg.sender) > 0, "You are not a owner."); mint(_tier, _amount); } function whitelistSale(uint _tier, uint256 _amount) public payable{ require(whitelistSaleTime[0] <= block.timestamp && whitelistSaleTime[1] > block.timestamp, "Whitelist sale not started!"); require(whitelist[msg.sender] > 0, "You are not on whitelist."); require(whitelist[msg.sender] >= _amount, "You can not mint this amount."); whitelist[msg.sender] -= _amount; mint(_tier, _amount); } function updateWhitelist(address[] memory _addresses, uint _amount) public onlyOwner{ for(uint256 i = 0; i < _addresses.length; i++){ whitelist[_addresses[i]] = _amount; } } function updateWhitelistSale(uint256 _startTime, uint256 _endTime) public onlyOwner{ whitelistSaleTime[0] = _startTime; whitelistSaleTime[1] = _endTime; } function updateOwnerSale(uint256 _startTime, uint256 _endTime) public onlyOwner{ ownerSaleTime[0] = _startTime; ownerSaleTime[1] = _endTime; } function updatePublicSale(uint256 _startTime, uint256 _endTime) public onlyOwner{ publicSaleTime[0] = _startTime; publicSaleTime[1] = _endTime; } function mint(uint _tier, uint256 _amount) internal { require(maxMintsPerTx >= _amount, "Over maximum mints per TX!"); require(_tier < mintValueByTier.length, "Tier not exists!"); uint256 _mintValue = mintValueByTier[_tier]; require(msg.value == _mintValue * _amount, "Invalid value sent!"); require(maxSupply >= (totalSupply + _amount), "Not enough symbio remaining!"); require(maxSupplyByTier[_tier] >= (totalSupplyByTier[_tier] + _amount), "Not enough symbio of this tier remaining!"); require(maxSupplyByTierOnPhase[actualPhase][_tier] >= (totalSupplyByTier[_tier] + _amount), "Not enough symbio of this tier remaining in this phase!"); for(uint256 i = 0; i < _amount; i++){ // Create a new symbiote symbiotes.push(Symbiote(_tier, _mintValue, block.timestamp, 0, 0, 0)); // Mint _mint(msg.sender, totalSupply + 1 + i); } // Update supply totalSupply += _amount; totalSupplyByTier[_tier] += _amount; } function setMintValueByTier(uint256 _tier, uint256 _value) public onlyOwner higherOrEqualZero(_value) { mintValueByTier[_tier] = _value; } function setMaxSupplyByTierOnPhase(uint256[6] memory _valuesByTier, uint256 _phase) public onlyOwner { maxSupplyByTierOnPhase[_phase] = _valuesByTier; } function setMaxMintsPerTx(uint256 _value) public onlyOwner { maxMintsPerTx = _value; } function setYield(uint256 _value) public onlyOwner { yield = _value; } function claimRewards(uint256 _tokenId, address payable _address) public isOwner(_tokenId){ // Get rewards unclaimed uint256 _total_rewards_unclaimed = updateAndGetTotalRewardsUnclaimed(_tokenId); require(address(this).balance > _total_rewards_unclaimed, "Balance of contract not enoght, try later!"); if(_total_rewards_unclaimed > 0){ //Update total rewards unclaimed symbiotes[_tokenId].total_rewards_unclaimed = 0; // Update total rewards claimed symbiotes[_tokenId].total_rewards_claimed += _total_rewards_unclaimed; _address.transfer(_total_rewards_unclaimed); emit ClaimRewards(_tokenId, _total_rewards_unclaimed); } } function updateAndGetTotalRewardsUnclaimed(uint256 _tokenId) public returns(uint256){ //Update total rewards unclaimed symbiotes[_tokenId].total_rewards_unclaimed = getTotalRewardsUnclaimed(_tokenId); //Update reward claimed at symbiotes[_tokenId].rewards_claimed_at = block.timestamp; //Return total rewards unclaimed return symbiotes[_tokenId].total_rewards_unclaimed; } function getTotalRewardsUnclaimed(uint256 _tokenId) public view returns(uint256){ // Set total rewards unclaimed uint256 totalRewardsUnclaimed = symbiotes[_tokenId].total_rewards_unclaimed + calculeStakeBalance(_tokenId); return totalRewardsUnclaimed; } function calculeStakeBalance(uint256 _tokenId) public view returns(uint256){ uint256 totalReward; uint256 timeStakingBySeconds; uint256 actualTime; actualTime = block.timestamp; timeStakingBySeconds = 0; // Calculate total brains staked if(symbiotes[_tokenId].rewards_claimed_at > 0){ timeStakingBySeconds = actualTime - symbiotes[_tokenId].rewards_claimed_at; }else{ timeStakingBySeconds = actualTime - symbiotes[_tokenId].stake_started_at; } totalReward = (yield * symbiotes[_tokenId].total_staked * timeStakingBySeconds) / 864000000; // Filter to 0 if(totalReward < 0){ totalReward = 0; } return totalReward; } function withdraw(uint256 amount) public onlyOwner { require(amount <= address(this).balance, "Amount should be equal or lower of balance."); payable(msg.sender).transfer(amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } /* * Events */ /* * Modifiers */ // Check owner of this symbiote is the same of msg sender modifier isOwner(uint256 _symbioteId) { require(msg.sender == ownerOf(_symbioteId), "Must be the owner of the symbiote"); _; } // check if number is higher or equal zero modifier higherOrEqualZero(uint256 _value) { require(_value >= 0, "Value need be higher or equal zero"); _; } /* * Event */ event ClaimRewards(uint256 _tokenId, uint256 value); }
First symbiote index 0
constructor() ERC721("Symbio", "SYMBIO"){ symbiotes.push(Symbiote(0, 0, 0, 0, 0, 0)); maxSupplyByTierOnPhase[0] = [ 33, 13, 3, 0, 0, 0]; maxSupplyByTierOnPhase[1] = [ 333, 33, 13, 3, 0, 0]; maxSupplyByTierOnPhase[2] = [1333, 333, 33, 13, 3, 0]; maxSupplyByTierOnPhase[3] = [2333, 1333, 333, 33, 13, 3]; maxSupplyByTierOnPhase[4] = [3333, 2333, 1333, 333, 33, 13]; maxSupplyByTierOnPhase[5] = [3333, 3333, 2333, 1333, 333, 33]; maxSupplyByTierOnPhase[6] = [3333, 3333, 3333, 2333, 1333, 333]; maxSupplyByTierOnPhase[7] = [3333, 3333, 3333, 3333, 2333, 1333]; maxSupplyByTierOnPhase[8] = [3333, 3333, 3333, 3333, 3333, 2333]; maxSupplyByTierOnPhase[9] = [3333, 3333, 3333, 3333, 3333, 3333]; }
5,777,068
[ 1, 3759, 1393, 1627, 77, 1168, 770, 374, 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, 202, 12316, 1435, 4232, 39, 27, 5340, 2932, 10876, 1627, 1594, 3113, 315, 7474, 7969, 4294, 7923, 95, 203, 565, 1393, 1627, 77, 6366, 18, 6206, 12, 10876, 1627, 77, 1168, 12, 20, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 10019, 203, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 20, 65, 273, 306, 225, 13159, 16, 282, 5958, 16, 565, 890, 16, 565, 374, 16, 565, 374, 16, 565, 374, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 21, 65, 273, 306, 890, 3707, 16, 282, 13159, 16, 282, 5958, 16, 565, 890, 16, 565, 374, 16, 565, 374, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 22, 65, 273, 306, 3437, 3707, 16, 225, 890, 3707, 16, 282, 13159, 16, 282, 5958, 16, 565, 890, 16, 565, 374, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 23, 65, 273, 306, 31026, 23, 16, 30537, 23, 16, 225, 890, 3707, 16, 282, 13159, 16, 282, 5958, 16, 565, 890, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 24, 65, 273, 306, 18094, 16, 576, 3707, 23, 16, 30537, 23, 16, 225, 890, 3707, 16, 282, 13159, 16, 282, 5958, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 25, 65, 273, 306, 18094, 16, 890, 3707, 23, 16, 576, 3707, 23, 16, 30537, 23, 16, 225, 890, 3707, 16, 282, 13159, 15533, 203, 565, 943, 3088, 1283, 858, 15671, 1398, 11406, 63, 26, 65, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./lib/Babylonian.sol"; import "./owner/Operator.sol"; import "./utils/ContractGuard.sol"; import "./interfaces/IBasisAsset.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/IBoardroom.sol"; /** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */ contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant PERIOD = 6 hours; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public migrated = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // core components address public cash; address public bond; address public share; address public boardroom; address public priceOracle; // price uint256 public peggedPrice; uint256 public cashPriceCeiling; uint256 public cashPriceCeilingForRedeemBond; // when redeeming bond uint256 public seigniorageSaved; // protocol parameters uint256 public maxSupplyExpansionPercent; uint256 public maxSupplyExpansionPercentInDebtPhase; uint256 public bondDepletionFloorPercent; uint256 public seigniorageBoardroomPercent; uint256 public seigniorageBoardroomPercentInDebtPhase; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; // Marketing Fund address public marketingFund; /* =================== Events =================== */ event Migration(address indexed target); event RedeemedBonds(address indexed from, uint256 cashAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 cashAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event MarketingFundFunded(uint256 timestamp, uint256 seigniorage); event ExpansionRateChanged(uint256 maxSupplyExpansionPercent, uint256 maxSupplyExpansionPercentInDebtPhase); event NewEpoch(uint256 epoch, uint256 cashPrice); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "onlyOperator"); _; } function checkCondition() private view { require(!migrated, "Migrated"); require(now >= startTime, "Not started yet"); } function checkEpoch() private { require(now >= nextEpochPoint(), "Not opened yet"); epoch = epoch.add(1); epochSupplyContractionLeft = IERC20(cash).totalSupply().mul(maxSupplyContractionPercent).div(10000); } function checkOperator() private view { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), "Permissions required" ); } constructor( address _cash, address _bond, address _share, address _priceOracle, address _marketingFund, uint256 _startTime ) public { require(block.timestamp < _startTime, "late"); cash = _cash; bond = _bond; share = _share; priceOracle = _priceOracle; marketingFund = _marketingFund; startTime = _startTime; peggedPrice = 0.5 ether; cashPriceCeiling = peggedPrice.mul(102).div(100); cashPriceCeilingForRedeemBond = peggedPrice.mul(130).div(100); maxSupplyExpansionPercent = 250; maxSupplyExpansionPercentInDebtPhase = 250; bondDepletionFloorPercent = 10000; seigniorageBoardroomPercent = 5000; seigniorageBoardroomPercentInDebtPhase = 5000; maxSupplyContractionPercent = 300; maxDebtRatioPercent = 3500; seigniorageSaved = IERC20(cash).balanceOf(address(this)); operator = msg.sender; } /* ========== VIEW FUNCTIONS ========== */ // flags function isMigrated() public view returns (bool) { return migrated; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } // oracle function getCashPrice() public view returns (uint256 cashPrice) { try IOracle(priceOracle).consult(cash, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Oracle consult cash price failed"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _totalCash = IERC20(cash).balanceOf(address(this)); uint256 _rate = getBondExchangeRate(); if (_rate > 0) { _redeemableBonds = _totalCash.mul(1e18).div(_rate); } } function getBondExchangeRate() public view returns (uint256 _rate) { uint256 _cashPrice = getCashPrice(); if (_cashPrice > cashPriceCeiling) { _rate = Math.min(_cashPrice, cashPriceCeilingForRedeemBond).mul(2); } else { _rate = 9**17; } } /* ========== GOVERNANCE ========== */ function setOperator(address _operator) external onlyOperator { operator = _operator; } function setBoardroom(address _boardroom) external onlyOperator { boardroom = _boardroom; } function setCashOracle(address _priceOracle) external onlyOperator { priceOracle = _priceOracle; } function setCashPriceCeiling(uint256 _cashPriceCeiling) external onlyOperator { require(_cashPriceCeiling >= peggedPrice && _cashPriceCeiling <= peggedPrice.mul(120).div(100), "out of range"); // [$0.5, $0.6] cashPriceCeiling = _cashPriceCeiling; } function setCashPriceMaxPremium(uint256 _cashPriceCeilingForRedeemBond) external onlyOperator { require(_cashPriceCeilingForRedeemBond >= peggedPrice && _cashPriceCeilingForRedeemBond <= peggedPrice.mul(200).div(100), "out of range"); // [$0.5, $1.0] cashPriceCeilingForRedeemBond = _cashPriceCeilingForRedeemBond; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent, uint256 _maxSupplyExpansionPercentInDebtPhase) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 3000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 30%] require( _maxSupplyExpansionPercentInDebtPhase >= 10 && _maxSupplyExpansionPercentInDebtPhase <= 3000, "_maxSupplyExpansionPercentInDebtPhase: out of range" ); // [0.1%, 30%] require( _maxSupplyExpansionPercent <= _maxSupplyExpansionPercentInDebtPhase, "_maxSupplyExpansionPercent is over _maxSupplyExpansionPercentInDebtPhase" ); maxSupplyExpansionPercent = _maxSupplyExpansionPercent; maxSupplyExpansionPercentInDebtPhase = _maxSupplyExpansionPercentInDebtPhase; emit ExpansionRateChanged(_maxSupplyExpansionPercent, _maxSupplyExpansionPercentInDebtPhase); } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 13000, "out of range"); // [5%, 130%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setSeigniorageBoardroomPercent(uint256 _seigniorageBoardroomPercent) external onlyOperator { require(_seigniorageBoardroomPercent >= 3000 && _seigniorageBoardroomPercent <= 10000, "out of range"); // [30%, 100%] seigniorageBoardroomPercent = _seigniorageBoardroomPercent; } function setSeigniorageBoardroomPercentInDebtPhase(uint256 _seigniorageBoardroomPercentInDebtPhase) external onlyOperator { require(_seigniorageBoardroomPercentInDebtPhase >= 3000 && _seigniorageBoardroomPercentInDebtPhase <= 10000, "out of range"); // [30%, 100%] seigniorageBoardroomPercentInDebtPhase = _seigniorageBoardroomPercentInDebtPhase; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 3000, "out of range"); // [0.1%, 30%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setMarketingFund(address _marketingFund) external onlyOperator { require(_marketingFund != address(0), "zero"); marketingFund = _marketingFund; } function migrate(address target) external onlyOperator { require(!migrated, "Migrated"); checkOperator(); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateCashPrice() internal { try IOracle(priceOracle).update() {} catch {} } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock { checkCondition(); checkOperator(); require(amount > 0, "Zero amount"); uint256 cashPrice = getCashPrice(); require(cashPrice == targetPrice, "Cash price moved"); require( cashPrice < peggedPrice, // price < $0.5 "CashPrice < 0.5" ); require(amount <= epochSupplyContractionLeft, "No bond left"); uint256 cashSupply = IERC20(cash).totalSupply(); uint256 newBondSupply = IERC20(bond).totalSupply().add(amount); require(newBondSupply <= cashSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(amount); _updateCashPrice(); emit BoughtBonds(msg.sender, amount, amount); } function redeemBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock { checkCondition(); checkOperator(); require(amount > 0, "Zero amount"); uint256 cashPrice = getCashPrice(); require(cashPrice == targetPrice, "Cash price moved"); uint256 _rate = getBondExchangeRate(); require(_rate > 0, "Invalid bond rate"); uint256 _cashAmount = amount.mul(_rate).div(1e18); require(IERC20(cash).balanceOf(address(this)) >= _cashAmount, "Treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _cashAmount)); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, _cashAmount); _updateCashPrice(); emit RedeemedBonds(msg.sender, _cashAmount, amount); } function _sendToBoardRoom(uint256 _amount) internal { IBasisAsset(cash).mint(address(this), _amount); IERC20(cash).safeApprove(boardroom, 0); IERC20(cash).safeApprove(boardroom, _amount); IBoardroom(boardroom).allocateSeigniorage(_amount); emit BoardroomFunded(now, _amount); } function allocateSeigniorage() external onlyOneBlock { checkCondition(); checkEpoch(); checkOperator(); _updateCashPrice(); uint256 cashSupply = IERC20(cash).totalSupply().sub(seigniorageSaved); uint256 cashPrice = getCashPrice(); emit NewEpoch(epoch, cashPrice); if (cashPrice > cashPriceCeiling) { uint256 bondSupply = IERC20(bond).totalSupply(); uint256 _percentage = cashPrice.sub(peggedPrice); if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate uint256 _mse = maxSupplyExpansionPercent.mul(1e14); if (_percentage > _mse) { _percentage = _mse; } uint256 _seigniorage = cashSupply.mul(_percentage).div(1e18); uint256 _savedForBoardRoom = _seigniorage.mul(seigniorageBoardroomPercent).div(10000); _sendToBoardRoom(_savedForBoardRoom); IBasisAsset(cash).mint(marketingFund, _seigniorage - _savedForBoardRoom); emit MarketingFundFunded(now, _seigniorage - _savedForBoardRoom); } else { // have not saved enough to pay debt, mint more uint256 _mse = maxSupplyExpansionPercentInDebtPhase.mul(1e14); if (_percentage > _mse) { _percentage = _mse; } uint256 _seigniorage = cashSupply.mul(_percentage).div(1e18); uint256 _savedForBoardRoom = _seigniorage.mul(seigniorageBoardroomPercentInDebtPhase).div(10000); _sendToBoardRoom(_savedForBoardRoom); uint256 _savedForBond = _seigniorage.sub(_savedForBoardRoom); seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(cash).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } /* ========== RECOVER UNSUPPORTED ========== */ function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(cash), "cash"); require(address(_token) != address(bond), "bond"); require(address(_token) != address(share), "share"); _token.safeTransfer(_to, _amount); } /* ========== BOARDROOM CONTROLLING FUNCTIONS ========== */ function boardroomSetOperator(address _operator) external onlyOperator { IBoardroom(boardroom).setOperator(_operator); } function boardroomSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { IBoardroom(boardroom).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function boardroomAllocateSeigniorage(uint256 amount) external onlyOperator { IBoardroom(boardroom).allocateSeigniorage(amount); } function boardroomGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { IBoardroom(boardroom).governanceRecoverUnsupported(_token, _amount, _to); } }
saved enough to pay debt, mint as usual rate
function allocateSeigniorage() external onlyOneBlock { checkCondition(); checkEpoch(); checkOperator(); _updateCashPrice(); uint256 cashSupply = IERC20(cash).totalSupply().sub(seigniorageSaved); uint256 cashPrice = getCashPrice(); emit NewEpoch(epoch, cashPrice); if (cashPrice > cashPriceCeiling) { uint256 bondSupply = IERC20(bond).totalSupply(); uint256 _percentage = cashPrice.sub(peggedPrice); if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { uint256 _mse = maxSupplyExpansionPercent.mul(1e14); if (_percentage > _mse) { _percentage = _mse; } uint256 _seigniorage = cashSupply.mul(_percentage).div(1e18); uint256 _savedForBoardRoom = _seigniorage.mul(seigniorageBoardroomPercent).div(10000); _sendToBoardRoom(_savedForBoardRoom); IBasisAsset(cash).mint(marketingFund, _seigniorage - _savedForBoardRoom); emit MarketingFundFunded(now, _seigniorage - _savedForBoardRoom); if (_percentage > _mse) { _percentage = _mse; } uint256 _seigniorage = cashSupply.mul(_percentage).div(1e18); uint256 _savedForBoardRoom = _seigniorage.mul(seigniorageBoardroomPercentInDebtPhase).div(10000); _sendToBoardRoom(_savedForBoardRoom); uint256 _savedForBond = _seigniorage.sub(_savedForBoardRoom); seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(cash).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } }
12,536,001
[ 1, 14077, 7304, 358, 8843, 18202, 88, 16, 312, 474, 487, 25669, 4993, 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, 10101, 1761, 724, 77, 1531, 1435, 3903, 1338, 3335, 1768, 288, 203, 3639, 866, 3418, 5621, 203, 3639, 866, 14638, 5621, 203, 3639, 866, 5592, 5621, 203, 3639, 389, 2725, 39, 961, 5147, 5621, 203, 3639, 2254, 5034, 276, 961, 3088, 1283, 273, 467, 654, 39, 3462, 12, 71, 961, 2934, 4963, 3088, 1283, 7675, 1717, 12, 307, 724, 77, 1531, 16776, 1769, 203, 3639, 2254, 5034, 276, 961, 5147, 273, 1927, 961, 5147, 5621, 203, 203, 3639, 3626, 1166, 14638, 12, 12015, 16, 276, 961, 5147, 1769, 203, 3639, 309, 261, 71, 961, 5147, 405, 276, 961, 5147, 39, 73, 4973, 13, 288, 203, 5411, 2254, 5034, 8427, 3088, 1283, 273, 467, 654, 39, 3462, 12, 26425, 2934, 4963, 3088, 1283, 5621, 203, 5411, 2254, 5034, 389, 18687, 273, 276, 961, 5147, 18, 1717, 12, 9001, 2423, 5147, 1769, 203, 2398, 203, 5411, 309, 261, 307, 724, 77, 1531, 16776, 1545, 8427, 3088, 1283, 18, 16411, 12, 26425, 758, 1469, 285, 42, 5807, 8410, 2934, 2892, 12, 23899, 3719, 288, 203, 7734, 2254, 5034, 389, 81, 307, 273, 943, 3088, 1283, 2966, 12162, 8410, 18, 16411, 12, 21, 73, 3461, 1769, 203, 7734, 309, 261, 67, 18687, 405, 389, 81, 307, 13, 288, 203, 10792, 389, 18687, 273, 389, 81, 307, 31, 203, 7734, 289, 203, 7734, 2254, 5034, 389, 307, 724, 77, 1531, 273, 276, 961, 3088, 1283, 18, 16411, 24899, 18687, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 7734, 2254, 5034, 389, 14077, 1290, 22233, 13646, 273, 389, 2 ]
./partial_match/42/0xAe7f87Bd18685e390736c9137D824754CCA80D06/sources/Orchestrator.sol
* @title uFragments ERC20 token @dev This is part of an implementation of the uFragments Ideal Money protocol. uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets. uFragment balances are internally represented with a hidden denomination, 'gons'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'gons' and the public 'fragments'./ PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of gons that equals 1 fragment. The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is always the denominator. (i.e. If you want to convert gons to fragments instead of multiplying by the inverse rate, you should divide by the normal rate) 2) Gon balances converted into Fragments are always rounded down (truncated). We make the following guarantees: - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will be decreased by precisely x Fragments, and B's external balance will be precisely increased by x Fragments. We do not guarantee that the sum of all balances equals the result of calling totalSupply(). This is because, for any conversion function 'f()' that has non-zero rounding error, f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). Used for authentication
contract UFragments is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogRebasePaused(bool paused); event LogTokenPaused(bool paused); event LogMonetaryPolicyUpdated(address monetaryPolicy); address public monetaryPolicy; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool public tokenPaused; bool public rebasePaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } modifier whenTokenNotPaused() { require(!tokenPaused); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 25 * 10**4 * 10**DECIMALS; (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); uint256 private _totalSupply; uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; uint256 private constant TOTAL_GONS = MAX_UINT256 - mapping(address => mapping(address => uint256)) private _allowedFragments; function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } function setTokenPaused(bool paused) external onlyOwner { tokenPaused = paused; emit LogTokenPaused(paused); } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } } else { function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("DogeStop", "DOGES", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; tokenPaused = false; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonBalances[owner_] = TOTAL_GONS; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address who) public view returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } function transfer(address to, uint256 value) public validRecipient(to) whenTokenNotPaused returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } function transferFrom( address from, address to, uint256 value ) public validRecipient(to) whenTokenNotPaused returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg .sender] .sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public whenTokenNotPaused returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public whenTokenNotPaused returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg .sender][spender] .add(addedValue); emit Approval( msg.sender, spender, _allowedFragments[msg.sender][spender] ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public whenTokenNotPaused returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; _allowedFragments[msg.sender][spender] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedFragments[msg.sender][spender] ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public whenTokenNotPaused returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; _allowedFragments[msg.sender][spender] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedFragments[msg.sender][spender] ); return true; } } else { }
9,070,008
[ 1, 89, 27588, 4232, 39, 3462, 1147, 225, 1220, 353, 1087, 434, 392, 4471, 434, 326, 582, 27588, 23062, 287, 16892, 1771, 18, 1377, 582, 27588, 353, 279, 2212, 4232, 39, 3462, 1147, 16, 1496, 2097, 14467, 848, 506, 13940, 635, 20347, 471, 1377, 29189, 2430, 23279, 1230, 10279, 777, 17662, 2413, 18, 1377, 582, 7456, 324, 26488, 854, 12963, 10584, 598, 279, 5949, 10716, 1735, 16, 296, 75, 7008, 10332, 1377, 1660, 2865, 20347, 326, 5462, 316, 17965, 471, 29189, 326, 5462, 603, 16252, 1128, 635, 1377, 12770, 326, 7829, 4993, 3086, 326, 5949, 296, 75, 7008, 11, 471, 326, 1071, 296, 29528, 10332, 19, 453, 22357, 10746, 21203, 6469, 3388, 1360, 16743, 29437, 1360, 4869, 28394, 5502, 957, 1915, 353, 16536, 16, 1915, 353, 279, 18404, 434, 17409, 1804, 2967, 628, 13885, 1334, 18, 657, 1353, 358, 18935, 333, 18404, 16, 732, 1261, 14852, 358, 326, 3751, 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, 587, 27588, 353, 4232, 39, 3462, 40, 6372, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 203, 565, 871, 1827, 426, 1969, 12, 11890, 5034, 8808, 7632, 16, 2254, 5034, 2078, 3088, 1283, 1769, 203, 565, 871, 1827, 426, 1969, 28590, 12, 6430, 17781, 1769, 203, 565, 871, 1827, 1345, 28590, 12, 6430, 17781, 1769, 203, 565, 871, 1827, 11415, 14911, 2582, 7381, 12, 2867, 31198, 2582, 1769, 203, 203, 565, 1758, 1071, 31198, 2582, 31, 203, 203, 203, 565, 9606, 1338, 11415, 14911, 2582, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 31198, 2582, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 1426, 1071, 1147, 28590, 31, 203, 203, 565, 1426, 1071, 283, 1969, 28590, 31, 203, 565, 9606, 1347, 426, 1969, 1248, 28590, 1435, 288, 203, 3639, 2583, 12, 5, 266, 1969, 28590, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1347, 1345, 1248, 28590, 1435, 288, 203, 3639, 2583, 12, 5, 2316, 28590, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 923, 18241, 12, 2867, 358, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 12, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 2468, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 57, 3217, 5034, 273, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.11; /** * @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() { 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 DebtToken { using SafeMath for uint256; /** Recognition data */ string public name; string public symbol; string public version = 'DT0.1'; uint256 public decimals = 18; /** ERC20 properties */ uint256 public totalSupply; mapping(address => uint256) public balances; event Transfer(address indexed from, address indexed to, uint256 value); /** Mintable Token properties */ bool public mintingFinished = true; event Mint(address indexed to, uint256 amount); event MintFinished(); /** Actual logic data */ uint256 public dayLength;//Number of seconds in a day uint256 public loanTerm;//Loan term in days uint256 public exchangeRate; //Exchange rate for Ether to loan coins uint256 public initialSupply; //Keep record of Initial value of Loan uint256 public loanActivation; //Timestamp the loan was funded uint256 public interestRatePerCycle; //Interest rate per interest cycle uint256 public interestCycleLength; //Total number of days per interest cycle uint256 public totalInterestCycles; //Total number of interest cycles completed uint256 public lastInterestCycle; //Keep record of Initial value of Loan address public lender; //The address from which the loan will be funded, and to which the refund will be directed address public borrower; uint256 public constant PERCENT_DIVISOR = 100; function DebtToken( string _tokenName, string _tokenSymbol, uint256 _initialAmount, uint256 _exchangeRate, uint256 _dayLength, uint256 _loanTerm, uint256 _loanCycle, uint256 _interestRatePerCycle, address _lender, address _borrower ) { require(_exchangeRate > 0); require(_initialAmount > 0); require(_dayLength > 0); require(_loanCycle > 0); require(_lender != 0x0); require(_borrower != 0x0); exchangeRate = _exchangeRate; // Exchange rate for the coins initialSupply = _initialAmount.mul(exchangeRate); // Update initial supply totalSupply = initialSupply; //Update total supply balances[_borrower] = initialSupply; // Give the creator all initial tokens name = _tokenName; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes dayLength = _dayLength; //Set the length of each day in seconds...For dev purposes loanTerm = _loanTerm; //Set the number of days, for loan maturity interestCycleLength = _loanCycle; //set the Interest cycle period interestRatePerCycle = _interestRatePerCycle; //Set the Interest rate per cycle lender = _lender; //set lender address borrower = _borrower; Transfer(0,_borrower,totalSupply);//Allow funding be tracked } /** Debt token functionality */ function actualTotalSupply() public constant returns(uint) { uint256 coins; uint256 cycle; (coins,cycle) = calculateInterestDue(); return totalSupply.add(coins); } /** Fetch total value of loan in wei (Initial +interest) */ function getLoanValue(bool initial) public constant returns(uint){ //TODO get a more dynamic way to calculate if(initial == true) return initialSupply.div(exchangeRate); else{ uint totalTokens = actualTotalSupply().sub(balances[borrower]); return totalTokens.div(exchangeRate); } } /** Fetch total coins gained from interest */ function getInterest() public constant returns (uint){ return actualTotalSupply().sub(initialSupply); } /** Checks that caller's address is the lender */ function isLender() private constant returns(bool){ return msg.sender == lender; } /** Check that caller's address is the borrower */ function isBorrower() private constant returns (bool){ return msg.sender == borrower; } function isLoanFunded() public constant returns(bool) { return balances[lender] > 0 && balances[borrower] == 0; } /** Check if the loan is mature for interest */ function isTermOver() public constant returns (bool){ if(loanActivation == 0) return false; else return now >= loanActivation.add( dayLength.mul(loanTerm) ); } /** Check if updateInterest() needs to be called before refundLoan() */ function isInterestStatusUpdated() public constant returns(bool){ if(!isTermOver()) return true; else return !( now >= lastInterestCycle.add( interestCycleLength.mul(dayLength) ) ); } /** calculate the total number of passed interest cycles and coin value */ function calculateInterestDue() public constant returns(uint256 _coins,uint256 _cycle){ if(!isTermOver() || !isLoanFunded()) return (0,0); else{ uint timeDiff = now.sub(lastInterestCycle); _cycle = timeDiff.div(dayLength.mul(interestCycleLength) ); _coins = _cycle.mul( interestRatePerCycle.mul(initialSupply) ).div(PERCENT_DIVISOR);//Delayed division to avoid too early floor } } /** Update the interest of the contract */ function updateInterest() public { require( isTermOver() ); uint interest_coins; uint256 interest_cycle; (interest_coins,interest_cycle) = calculateInterestDue(); assert(interest_coins > 0 && interest_cycle > 0); totalInterestCycles = totalInterestCycles.add(interest_cycle); lastInterestCycle = lastInterestCycle.add( interest_cycle.mul( interestCycleLength.mul(dayLength) ) ); mint(lender , interest_coins); } /** Make payment to inititate loan */ function fundLoan() public payable{ require(isLender()); require(msg.value == getLoanValue(true)); //Ensure input available require(!isLoanFunded()); //Avoid double payment loanActivation = now; //store the time loan was activated lastInterestCycle = now.add(dayLength.mul(loanTerm) ) ; //store the date interest matures mintingFinished = false; //Enable minting transferFrom(borrower,lender,totalSupply); borrower.transfer(msg.value); } /** Make payment to refund loan */ function refundLoan() onlyBorrower public payable{ if(! isInterestStatusUpdated() ) updateInterest(); //Ensure Interest is updated require(msg.value == getLoanValue(false)); require(isLoanFunded()); finishMinting() ;//Prevent further Minting transferFrom(lender,borrower,totalSupply); lender.transfer(msg.value); } /** Partial ERC20 functionality */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) internal { require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); } /** MintableToken functionality */ modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) canMint internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyBorrower internal returns (bool) { mintingFinished = true; MintFinished(); return true; } /** Fallback function */ function() public payable{ require(initialSupply > 0);//Stop the whole process if initialSupply not set if(isBorrower()) refundLoan(); else if(isLender()) fundLoan(); else revert(); //Throw if neither of cases apply, ensure no free money } /** Modifiers */ modifier onlyBorrower() { require(isBorrower()); _; } } contract DebtTokenDeployer is Ownable{ address public dayTokenAddress; uint public dayTokenFees; //DAY tokens to be paid for deploying custom DAY contract ERC20 dayToken; event FeeUpdated(uint _fee, uint _time); event DebtTokenCreated(address _creator, address _debtTokenAddress, uint256 _time); function DebtTokenDeployer(address _dayTokenAddress, uint _dayTokenFees){ dayTokenAddress = _dayTokenAddress; dayTokenFees = _dayTokenFees; dayToken = ERC20(dayTokenAddress); } function updateDayTokenFees(uint _dayTokenFees) onlyOwner public { dayTokenFees = _dayTokenFees; FeeUpdated(dayTokenFees, now); } function createDebtToken(string _tokenName, string _tokenSymbol, uint256 _initialAmount, uint256 _exchangeRate, uint256 _dayLength, uint256 _loanTerm, uint256 _loanCycle, uint256 _intrestRatePerCycle, address _lender) public { if(dayToken.transferFrom(msg.sender, this, dayTokenFees)){ DebtToken newDebtToken = new DebtToken(_tokenName, _tokenSymbol, _initialAmount, _exchangeRate, _dayLength, _loanTerm, _loanCycle, _intrestRatePerCycle, _lender, msg.sender); DebtTokenCreated(msg.sender, address(newDebtToken), now); } } // to collect all fees paid till now function fetchDayTokens() onlyOwner public { dayToken.transfer(owner, dayToken.balanceOf(this)); } }
Total number of interest cycles completed
uint256 public totalInterestCycles;
7,217,151
[ 1, 5269, 1300, 434, 16513, 15139, 5951, 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, 2254, 5034, 1071, 2078, 29281, 17992, 9558, 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 ]
./full_match/80001/0x1C14B2a002367FDb0e03CBa23d63AA3b1f5096d9/sources/project_/contracts/superfluid/FlowNFTBase.sol
@note taking this out to deal with the stack too deep issue which occurs when you are attempting to abi.encodePacked too many elements @note upcasting is safe
function _flowDataString( uint256 tokenId ) internal view returns (string memory) { FlowNFTData memory flowData = flowDataByTokenId(tokenId); return string( abi.encodePacked( "&token_address=", Strings.toHexString( uint256(uint160(flowData.superToken)), 20 ), "?chain_id=", block.chainid.toString(), "&token_symbol=", ISuperToken(flowData.superToken).symbol(), "&sender=", Strings.toHexString( uint256(uint160(flowData.flowSender)), 20 ), "&receiver=", Strings.toHexString( uint256(uint160(flowData.flowReceiver)), 20 ), "&token_decimals=", uint256(ISuperToken(flowData.superToken).decimals()) .toString(), "&start_date=", uint256(flowData.flowStartDate).toString() ) ); }
5,674,425
[ 1, 36, 7652, 13763, 333, 596, 358, 10490, 598, 326, 2110, 4885, 4608, 5672, 1492, 9938, 1347, 1846, 854, 15600, 358, 24126, 18, 3015, 4420, 329, 4885, 4906, 2186, 632, 7652, 731, 4155, 310, 353, 4183, 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, 389, 2426, 751, 780, 12, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 9473, 50, 4464, 751, 3778, 4693, 751, 273, 4693, 751, 858, 1345, 548, 12, 2316, 548, 1769, 203, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 7830, 2316, 67, 2867, 1546, 16, 203, 10792, 8139, 18, 869, 14866, 12, 203, 13491, 2254, 5034, 12, 11890, 16874, 12, 2426, 751, 18, 9565, 1345, 13, 3631, 203, 13491, 4200, 203, 10792, 262, 16, 203, 10792, 18101, 5639, 67, 350, 1546, 16, 203, 10792, 1203, 18, 5639, 350, 18, 10492, 9334, 203, 10792, 7830, 2316, 67, 7175, 1546, 16, 203, 10792, 467, 8051, 1345, 12, 2426, 751, 18, 9565, 1345, 2934, 7175, 9334, 203, 10792, 7830, 15330, 1546, 16, 203, 10792, 8139, 18, 869, 14866, 12, 203, 13491, 2254, 5034, 12, 11890, 16874, 12, 2426, 751, 18, 2426, 12021, 13, 3631, 203, 13491, 4200, 203, 10792, 262, 16, 203, 10792, 7830, 24454, 1546, 16, 203, 10792, 8139, 18, 869, 14866, 12, 203, 13491, 2254, 5034, 12, 11890, 16874, 12, 2426, 751, 18, 2426, 12952, 13, 3631, 203, 13491, 4200, 203, 10792, 262, 16, 203, 10792, 7830, 2316, 67, 31734, 1546, 16, 203, 10792, 2254, 5034, 12, 45, 8051, 1345, 12, 2426, 751, 18, 9565, 1345, 2934, 31734, 10756, 203, 13491, 263, 10492, 9334, 203, 10792, 7830, 1937, 67, 712, 1546, 16, 203, 10792, 2254, 5034, 12, 2426, 751, 18, 2426, 22635, 2934, 2 ]
./full_match/1/0x6D5Ac9cE19f996C33D810cf2ea62623C4Cbcaa28/sources/collector.sol
update _receivedPermissionNumber first
uint receivedPermissionNumber = _receivedPermissionNumber;
2,962,621
[ 1, 2725, 389, 15213, 5041, 1854, 1122, 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, 2254, 5079, 5041, 1854, 273, 389, 15213, 5041, 1854, 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 ]
./full_match/3/0x8A88015b8f9E54b47F24E3746a23167B079BFceb/sources/browser/3_balancer/1_code/Math.sol
* @dev Standard math utilities missing in the Solidity language./
library Math { pragma solidity ^0.6.0; 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; } function average(uint256 a, uint256 b) internal pure returns (uint256) { return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
8,265,525
[ 1, 8336, 4233, 22538, 3315, 316, 326, 348, 7953, 560, 2653, 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, 12083, 2361, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 565, 445, 943, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 279, 1545, 324, 692, 279, 294, 324, 31, 203, 565, 289, 203, 203, 565, 445, 1131, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 279, 411, 324, 692, 279, 294, 324, 31, 203, 565, 289, 203, 203, 565, 445, 8164, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 261, 69, 342, 576, 13, 397, 261, 70, 342, 576, 13, 397, 14015, 69, 738, 576, 397, 324, 738, 576, 13, 342, 576, 1769, 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 ]
// 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; } }
* @dev emitted on migration @param sender the caller of the migration @param amount the amount being migrated/* @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; }
15,782,311
[ 1, 351, 11541, 603, 6333, 225, 5793, 326, 4894, 434, 326, 6333, 225, 3844, 326, 3844, 3832, 24741, 19, 225, 279, 836, 326, 1758, 434, 326, 432, 26714, 1147, 225, 328, 409, 326, 1758, 434, 326, 511, 4415, 1147, 225, 328, 409, 37, 836, 8541, 326, 7829, 4993, 3086, 511, 4415, 471, 432, 26714, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 45, 654, 39, 3462, 279, 836, 16, 467, 654, 39, 3462, 328, 409, 16, 2254, 5034, 328, 409, 37, 836, 8541, 13, 1071, 288, 203, 3639, 432, 26714, 273, 279, 836, 31, 203, 3639, 511, 4415, 273, 328, 409, 31, 203, 3639, 511, 4415, 67, 5284, 3412, 67, 54, 789, 4294, 273, 328, 409, 37, 836, 8541, 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 ]
pragma solidity ^0.4.24; import "./SimpleToken.sol"; import "./Buck.sol"; /** * @title ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20.sol */ contract Likoin is SimpleToken{ // the token being converted to Buck private _buck; // How many bucks a buyer gets per token. uint256 private _conversionRate; // Balances mapping (address => uint256[2]) _balances; // Allowances mapping, used to allow an address to spend another address tokens mapping (address => mapping (address => uint256)) private _allowed; // Addresses of holders, list that starts from 1 mapping (uint256 => address) private _balanceHolders; // Index of last holder in list uint256 _holdersIndex; /** * Event for token conversion */ event TokensConversion(address indexed beneficiary, uint256 amount); /** * Event for an approval */ event Approval( address indexed owner, address indexed spender, uint256 value); /** * @param assignee Address of the entity token depends on * @param buck Address of the token used for conversion * @param conversionRate Number of buck units a buyer gets per tokens * @param name Token name * @param symbol Token symbol */ constructor(address assignee, Buck buck, uint256 conversionRate, string name, string symbol) public { require(conversionRate > 0); require(assignee != address(0)); require(buck != address(0)); _owner = msg.sender; _assignee = assignee; _addMinter(msg.sender); _addMinter(assignee); _name = name; _symbol = symbol; _buck = buck; _conversionRate = conversionRate; } /** * @dev Transfer token to a specified address */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev The way in which tokens are converted to bucks. */ function convertToBucks(uint256 value) public returns (bool success) { require(balanceOf(msg.sender) >= value); _shareToken(msg.sender, value); emit TokensConversion(msg.sender, value); uint256 bucks = value * _conversionRate; _buck.mint(msg.sender, bucks); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another if the address from approved msg.sender */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from][0]); require(to != address(0)); if(_balances[to][0] <= 0){ _addHolder(to); } _balances[from][0] = _balances[from][0].sub(value); _balances[to][0] = _balances[to][0].add(value); if(_balances[from][0] <= 0){ _removeHolder(from); } emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. */ function _mint(address account, uint256 value) internal { require(account != 0); if(_balances[account][0] <= 0){ _addHolder(account); } _totalSupply = _totalSupply.add(value); _balances[account][0] = _balances[account][0].add(value); emit Transfer(address(0), account, value); } /** * @dev Share value tokens between all addresses except from */ function _shareToken(address from, uint256 value) internal returns (bool) { for(uint i = 1; i <= _holdersIndex; i++){ if(to != from){ address to = _balanceHolders[i]; uint256 bal = balanceOf(to); _transfer(from, to, value.mul(bal.div(_totalSupply.sub(value)))); //value * ( balance[to] / (totalSupply-value) ) } } return true; } /** * @dev Internal function that burns an amount of the token of a given * account. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account][0]); _totalSupply = _totalSupply.sub(value); _balances[account][0] = _balances[account][0].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); if(_balances[account][0] <= 0){ _removeHolder(account); } } /** * @dev Internal function that adds an holder */ function _addHolder(address account) internal { _balanceHolders[++_holdersIndex] = account; _balances[account][1] = _holdersIndex; } /** * @dev Internal function that removes an holder */ function _removeHolder(address account) internal { uint256 index = _balances[account][1]; if (index < 1) return; if(_holdersIndex > 1){ address last = _balanceHolders[_holdersIndex]; _balanceHolders[index] = last; _balances[last][1] = index; } _holdersIndex--; _balances[account][1] = 0; } /** * @return the token being used for conversion. */ function buck() public view returns(Buck) { return _buck; } /** * @return the number of buck units a buyer gets per token. */ function conversionRate() public view returns(uint256) { return _conversionRate; } /** * @dev Gets the balance of the specified address. */ function balanceOf(address account) public view returns (uint256) { return _balances[account][0]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Function that returns the balanceHolders length */ function getBalanceHoldersLength() public view returns (uint256) { return _holdersIndex; } /** * @dev Function that returns the address in position i of balanceHolders */ function getBalanceHolder(uint256 i) public view returns (address) { require (i <= _holdersIndex); return _balanceHolders[i]; } }
* @dev Transfer tokens from one address to another if the address from approved msg.sender/
function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; }
889,028
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 309, 326, 1758, 628, 20412, 1234, 18, 15330, 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, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 1132, 1648, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 565, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 8009, 1717, 12, 1132, 1769, 203, 565, 389, 13866, 12, 2080, 16, 358, 16, 460, 1769, 203, 565, 327, 638, 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 ]
//Address: 0x449f5c827cf7726cc5f181090aa147ca5fb88a40 //Contract name: EthergotchiOwnershipV2 //Balance: 0 Ether //Verification Date: 3/26/2018 //Transacion Count: 380 // CODE STARTS HERE pragma solidity ^0.4.19; /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _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) external view returns (uint256); /// @notice Find the owner of an NFT /// @param _tokenId The identifier for an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @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,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 data) external; /// @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) external; /// @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 `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. /// @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) external; /// @notice Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev 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) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all your assets. /// @dev Throws unless `msg.sender` is the current NFT owner. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @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) external view returns (address); /// @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) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x780e9d63 interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } contract Ownable { address private owner; event LogOwnerChange(address _owner); // Modify method to only allow calls from the owner of the contract. modifier onlyOwner() { require(msg.sender == owner); _; } function Ownable() public { owner = msg.sender; } /** * Replace the contract owner with a new owner. * * Parameters * ---------- * _owner : address * The address to replace the current owner with. */ function replaceOwner(address _owner) external onlyOwner { owner = _owner; LogOwnerChange(_owner); } } contract Controllable is Ownable { // Mapping of a contract address to its position in the list of active // contracts. This allows an O(1) look-up of the contract address compared // to a linear search within an array. mapping(address => uint256) private contractIndices; // The list of contracts that are allowed to call the contract-restricted // methods of contracts that extend this `Controllable` contract. address[] private contracts; /** * Modify method to only allow calls from active contract addresses. * * Notes * ----- * The zero address is considered an inactive address, as it is impossible * for users to send a call from that address. */ modifier onlyActiveContracts() { require(contractIndices[msg.sender] != 0); _; } function Controllable() public Ownable() { // The zeroth index of the list of active contracts is occupied by the // zero address to ensure that an index of zero can be used to indicate // that the contract address is inactive. contracts.push(address(0)); } /** * Add a contract address to the list of active contracts. * * Parameters * ---------- * _address : address * The contract address to add to the list of active contracts. */ function activateContract(address _address) external onlyOwner { require(contractIndices[_address] == 0); contracts.push(_address); // The index of the newly added contract is equal to the length of the // array of active contracts minus one, as Solidity is a zero-based // language. contractIndices[_address] = contracts.length - 1; } /** * Remove a contract address from the list of active contracts. * * Parameters * ---------- * _address : address * The contract address to remove from the list of active contracts. */ function deactivateContract(address _address) external onlyOwner { require(contractIndices[_address] != 0); // Get the last contract in the array of active contracts. This address // will be used to overwrite the address that will be removed. address lastActiveContract = contracts[contracts.length - 1]; // Overwrite the address that is to be removed with the value of the // last contract in the list. There is a possibility that these are the // same values, in which case nothing happens. contracts[contractIndices[_address]] = lastActiveContract; // Reduce the contracts array size by one, as the last contract address // will have been successfully moved. contracts.length--; // Set the address mapping to zero, effectively rendering the contract // banned from calling this contract. contractIndices[_address] = 0; } /** * Get the list of active contracts for this contract. * * Returns * ------- * address[] * The list of contract addresses that are allowed to call the * contract-restricted methods of this contract. */ function getActiveContracts() external view returns (address[]) { return contracts; } } library Tools { /** * Concatenate two strings. * * Parameters * ---------- * stringLeft : string * A string to concatenate with another string. This is the left part. * stringRight : string * A string to concatenate with another string. This is the right part. * * Returns * ------- * string * The resulting string from concatenating the two given strings. */ function concatenate( string stringLeft, string stringRight ) internal pure returns (string) { // Get byte representations of both strings to allow for one-by-one // character iteration. bytes memory stringLeftBytes = bytes(stringLeft); bytes memory stringRightBytes = bytes(stringRight); // Initialize new string holder with the appropriate number of bytes to // hold the concatenated string. string memory resultString = new string( stringLeftBytes.length + stringRightBytes.length ); // Get a bytes representation of the result string to allow for direct // modification. bytes memory resultBytes = bytes(resultString); // Initialize a number to hold the current index of the result string // to assign a character to. uint k = 0; // First loop over the left string, and afterwards over the right // string to assign each character to its proper location in the new // string. for (uint i = 0; i < stringLeftBytes.length; i++) { resultBytes[k++] = stringLeftBytes[i]; } for (i = 0; i < stringRightBytes.length; i++) { resultBytes[k++] = stringRightBytes[i]; } return string(resultBytes); } /** * Convert 256-bit unsigned integer into a 32 bytes structure. * * Parameters * ---------- * value : uint256 * The unsigned integer to convert to bytes32. * * Returns * ------- * bytes32 * The bytes32 representation of the given unsigned integer. */ function uint256ToBytes32(uint256 value) internal pure returns (bytes32) { if (value == 0) { return '0'; } bytes32 resultBytes; while (value > 0) { resultBytes = bytes32(uint(resultBytes) / (2 ** 8)); resultBytes |= bytes32(((value % 10) + 48) * 2 ** (8 * 31)); value /= 10; } return resultBytes; } /** * Convert bytes32 data structure into a string. * * Parameters * ---------- * data : bytes32 * The bytes to convert to a string. * * Returns * ------- * string * The string representation of given bytes. * * Notes * ----- * This method is right-padded with zero bytes. */ function bytes32ToString(bytes32 data) internal pure returns (string) { bytes memory bytesString = new bytes(32); for (uint i = 0; i < 32; i++) { bytes1 char = bytes1(bytes32(uint256(data) * 2 ** (8 * i))); if (char != 0) { bytesString[i] = char; } } return string(bytesString); } } /** * Partial interface of former ownership contract. * * This interface is used to perform the migration of tokens, from the former * ownership contract to the current version. The inclusion of the entire * contract is too bulky, hence the partial interface. */ interface PartialOwnership { function ownerOf(uint256 _tokenId) external view returns (address); function totalSupply() external view returns (uint256); } /** * Ethergotchi Ownership Contract * * This contract governs the "non-fungible tokens" (NFTs) that represent the * various Ethergotchi owned by players within Aethia. * * The NFTs are implemented according to the standard described in EIP-721 as * it was on March 19th, 2018. * * In addition to the mentioned specification, a method was added to create new * tokens: `add(uint256 _tokenId, address _owner)`. This method can *only* be * called by activated Aethia game contracts. * * For more information on Aethia and/or Ethergotchi, visit the following * website: https://aethia.co */ contract EthergotchiOwnershipV2 is Controllable, ERC721, ERC721Enumerable, ERC721Metadata { // Direct mapping to keep track of token owners. mapping(uint256 => address) private ownerByTokenId; // Mapping that keeps track of all tokens owned by a specific address. This // allows for iteration by owner, and is implemented to be able to comply // with the enumeration methods described in the ERC721Enumerable interface. mapping(address => uint256[]) private tokenIdsByOwner; // Mapping that keeps track of a token"s position in an owner"s list of // tokens. This allows for constant time look-ups within the list, instead // of needing to iterate the list of tokens. mapping(uint256 => uint256) private ownerTokenIndexByTokenId; // Mapping that keeps track of addresses that are approved to make a // transfer of a token. Approval can only be given to a single address, but // can be overridden for modification or retraction purposes. mapping(uint256 => address) private approvedTransfers; // Mapping that keeps track of operators that are allowed to perform // actions on behalf of another address. An address is allowed to set more // than one operator. Operators can perform all actions on behalf on an // address, *except* for setting a different operator. mapping(address => mapping(address => bool)) private operators; // Total number of tokens governed by this contract. This allows for the // enumeration of all tokens, provided that tokens are created with their // identifiers being numbers, incremented by one. uint256 private totalTokens; // The ERC-165 identifier of the ERC-165 interface. This contract // implements the `supportsInterface` method to check whether other types // of standard interfaces are supported. bytes4 private constant INTERFACE_SIGNATURE_ERC165 = bytes4( keccak256("supportsInterface(bytes4)") ); // The ERC-165 identifier of the ERC-721 interface. This contract // implements all methods of the ERC-721 Enumerable interface, and uses // this identifier to supply the correct answer to a call to // `supportsInterface`. bytes4 private constant INTERFACE_SIGNATURE_ERC721 = bytes4( keccak256("balanceOf(address)") ^ keccak256("ownerOf(uint256)") ^ keccak256("safeTransferFrom(address,address,uint256,bytes)") ^ keccak256("safeTransferFrom(address,address,uint256)") ^ keccak256("transferFrom(address,address,uint256)") ^ keccak256("approve(address,uint256)") ^ keccak256("setApprovalForAll(address,bool)") ^ keccak256("getApproved(uint256)") ^ keccak256("isApprovedForAll(address,address)") ); // The ERC-165 identifier of the ERC-721 Enumerable interface. This // contract implements all methods of the ERC-721 Enumerable interface, and // uses this identifier to supply the correct answer to a call to // `supportsInterface`. bytes4 private constant INTERFACE_SIGNATURE_ERC721_ENUMERABLE = bytes4( keccak256("totalSupply()") ^ keccak256("tokenByIndex(uint256)") ^ keccak256("tokenOfOwnerByIndex(address,uint256)") ); // The ERC-165 identifier of the ERC-721 Metadata interface. This contract // implements all methods of the ERC-721 Metadata interface, and uses the // identifier to supply the correct answer to a `supportsInterface` call. bytes4 private constant INTERFACE_SIGNATURE_ERC721_METADATA = bytes4( keccak256("name()") ^ keccak256("symbol()") ^ keccak256("tokenURI(uint256)") ); // The ERC-165 identifier of the ERC-721 Token Receiver interface. This // is not implemented by this contract, but is used to identify the // response given by the receiving contracts, if the `safeTransferFrom` // method is used. bytes4 private constant INTERFACE_SIGNATURE_ERC721_TOKEN_RECEIVER = bytes4( keccak256("onERC721Received(address,uint256,bytes)") ); event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * Modify method to only allow calls if the token is valid. * * Notice * ------ * Ethergotchi are valid if they are owned by an address that is not the * zero address. */ modifier onlyValidToken(uint256 _tokenId) { require(ownerByTokenId[_tokenId] != address(0)); _; } /** * Modify method to only allow transfers from authorized callers. * * Notice * ------ * This method also adds a few checks against common transfer beneficiary * mistakes to prevent a subset of unintended transfers that cannot be * reverted. */ modifier onlyValidTransfers(address _from, address _to, uint256 _tokenId) { // Get owner of the token. This is used to check against various cases // where the caller is allowed to transfer the token. address tokenOwner = ownerByTokenId[_tokenId]; // Check whether the caller is allowed to transfer the token with given // identifier. The caller is allowed to perform the transfer in any of // the following cases: // 1. the caller is the owner of the token; // 2. the caller is approved by the owner of the token to transfer // that specific token; or // 3. the caller is approved as operator by the owner of the token, in // which case the caller is approved to perform any action on // behalf of the owner. require( msg.sender == tokenOwner || msg.sender == approvedTransfers[_tokenId] || operators[tokenOwner][msg.sender] ); // Check against accidental transfers to the common "wrong" addresses. // This includes the zero address, this ownership contract address, and // "non-transfers" where the same address is filled in for both `_from` // and `_to`. require( _to != address(0) && _to != address(this) && _to != _from ); _; } /** * Ethergotchi ownership contract constructor * * At the time of contract construction, an Ethergotchi is artificially * constructed to ensure that Ethergotchi are numbered starting from one. */ function EthergotchiOwnershipV2( address _formerContract ) public Controllable() { ownerByTokenId[0] = address(0); tokenIdsByOwner[address(0)].push(0); ownerTokenIndexByTokenId[0] = 0; // The migration index is initialized to 1 as the zeroth token need not // be migrated; it is already created during the construction of this // contract. migrationIndex = 1; formerContract = PartialOwnership(_formerContract); } /** * Add new token into circulation. * * Parameters * ---------- * _tokenId : uint256 * The identifier of the token to add into circulation. * _owner : address * The address of the owner who receives the newly added token. * * Notice * ------ * This method can only be called by active game contracts. Game contracts * are added and modified manually. These additions and modifications * always trigger an event for audit purposes. */ function add( uint256 _tokenId, address _owner ) external onlyActiveContracts { // Safety checks to prevent contracts from calling this method without // setting the proper arguments. require(_tokenId != 0 && _owner != address(0)); _add(_tokenId, _owner); // As per the standard, transfers of newly created tokens should always // originate from the zero address. Transfer(address(0), _owner, _tokenId); } /** * Check whether contract supports given interface. * * Parameters * ---------- * interfaceID : bytes4 * The four-bytes representation of an interface of which to check * whether this contract supports it. * * Returns * ------- * bool * True if given interface is supported, else False. * * Notice * ------ * It is expected that the `bytes4` values of interfaces are generated by * calling XOR on all function signatures of the interface. * * Technically more interfaces are supported, as some interfaces may be * subsets of the supported interfaces. This check is only to be used to * verify whether "standard interfaces" are supported. */ function supportsInterface( bytes4 interfaceID ) external view returns (bool) { return ( interfaceID == INTERFACE_SIGNATURE_ERC165 || interfaceID == INTERFACE_SIGNATURE_ERC721 || interfaceID == INTERFACE_SIGNATURE_ERC721_METADATA || interfaceID == INTERFACE_SIGNATURE_ERC721_ENUMERABLE ); } /** * Get the name of the token this contract governs ownership of. * * Notice * ------ * This is the collective name of the token. Individual tokens may be named * differently by their owners. */ function name() external pure returns (string) { return "Ethergotchi"; } /** * Get the symbol of the token this contract governs ownership of. * * Notice * ------ * This symbol has been explicitly changed to `ETHERGOTCHI` from `GOTCHI` * in the `PHOENIX` patch of Aethia to prevent confusion with older tokens. */ function symbol() external pure returns (string) { return "ETHERGOTCHI"; } /** * Get the URI pointing to a JSON file with metadata for a given token. * * Parameters * ---------- * _tokenId : uint256 * The identifier of the token to get the URI for. * * Returns * ------- * string * The URI pointing to a JSON file with metadata for the token with * given identifier. * * Notice * ------ * This method returns a string that may contain more than one null-byte, * because the conversion method is not ideal. */ function tokenURI(uint256 _tokenId) external view returns (string) { bytes32 tokenIdBytes = Tools.uint256ToBytes32(_tokenId); return Tools.concatenate( "https://aethia.co/ethergotchi/", Tools.bytes32ToString(tokenIdBytes) ); } /** * Get the number of tokens assigned to given owner. * * Parameters * ---------- * _owner : address * The address of the owner of which to get the number of owned tokens * of. * * Returns * ------- * uint256 * The number of tokens owned by given owner. * * Notice * ------ * Tokens owned by the zero address are considered invalid, as described in * the EIP 721 standard, and queries regarding the zero address will result * in the transaction being rejected. */ function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return tokenIdsByOwner[_owner].length; } /** * Get the address of the owner of given token. * * Parameters * ---------- * _tokenId : uint256 * The identifier of the token of which to get the owner"s address. * * Returns * ------- * address * The address of the owner of given token. * * Notice * ------ * Tokens owned by the zero address are considered invalid, as described in * the EIP 721 standard, and queries regarding the zero address will result * in the transaction being rejected. */ function ownerOf(uint256 _tokenId) external view returns (address) { // Store the owner in a temporary variable to avoid having to do the // lookup twice. address _owner = ownerByTokenId[_tokenId]; require(_owner != address(0)); return _owner; } /** * Transfer the ownership of given token from one address to another. * * Parameters * ---------- * _from : address * The benefactor address to transfer the given token from. * _to : address * The beneficiary address to transfer the given token to. * _tokenId : uint256 * The identifier of the token to transfer. * data : bytes * Non-specified data to send along the transfer towards the `to` * address that can be processed. * * Notice * ------ * This method performs a check to determine whether the receiving party is * a smart contract by calling the `_isContract` method. This works until * the `Serenity` update of Ethereum is deployed. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes data ) external onlyValidToken(_tokenId) { // Call the internal `_safeTransferFrom` method to avoid duplicating // the transfer code. _safeTransferFrom(_from, _to, _tokenId, data); } /** * Transfer the ownership of given token from one address to another. * * Parameters * ---------- * _from : address * The benefactor address to transfer the given token from. * _to : address * The beneficiary address to transfer the given token to. * _tokenId : uint256 * The identifier of the token to transfer. * * Notice * ------ * This method does exactly the same as calling the `safeTransferFrom` * method with the `data` parameter set to an empty bytes value: * `safeTransferFrom(_from, _to, _tokenId, "")` */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external onlyValidToken(_tokenId) { // Call the internal `_safeTransferFrom` method to avoid duplicating // the transfer code. _safeTransferFrom(_from, _to, _tokenId, ""); } /** * Transfer the ownership of given token from one address to another. * * Parameters * ---------- * _from : address * The benefactor address to transfer the given token from. * _to : address * The beneficiary address to transfer the given token to. * _tokenId : uint256 * The identifier of the token to transfer. * * Notice * ------ * This method performs a few rudimentary checks to determine whether the * receiving party can actually receive the token. However, it is still up * to the caller to ensure this is actually the case. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external onlyValidToken(_tokenId) onlyValidTransfers(_from, _to, _tokenId) { _transfer(_to, _tokenId); } /** * Approve the given address for the transfer of the given token. * * Parameters * ---------- * _approved : address * The address to approve. Approval allows the address to transfer the * given token to a different address. * _tokenId : uint256 * The identifier of the token to give transfer approval for. * * Notice * ------ * There is no specific method to revoke approvals, but the approval is * removed after the transfer has been completed. Additionally the owner * or operator may call the method with the zero address as `_approved` to * effectively revoke the approval. */ function approve(address _approved, uint256 _tokenId) external { address _owner = ownerByTokenId[_tokenId]; // Approval can only be given by the owner or an operator approved by // the owner. require(msg.sender == _owner || operators[_owner][msg.sender]); // Set address as approved for transfer. It can be the case that the // address was already set (e.g. this method was called twice in a row) // in which case this does not change anything. approvedTransfers[_tokenId] = _approved; Approval(msg.sender, _approved, _tokenId); } /** * Set approval for a third-party to manage all tokens of the caller. * * Parameters * ---------- * _operator : address * The address to set the operator status for. * _approved : bool * The operator status. True if the given address should be allowed to * act on behalf of the caller, else False. * * Notice * ------ * There is no duplicate checking done out of simplicity. Callers are thus * able to set the same address as operator a multitude of times, even if * it does not change the actual state of the system. */ function setApprovalForAll(address _operator, bool _approved) external { operators[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /** * Get approved address for given token. * * Parameters * ---------- * _tokenId : uint256 * The identifier of the token of which to get the approved address of. * * Returns * ------- * address * The address that is allowed to initiate a transfer of the given * token. * * Notice * ------ * Technically this method could be implemented without the method modifier * as the network guarantees that the address mapping is initiated with all * addresses set to the zero address. The requirement is implemented to * comply with the standard as described in EIP-721. */ function getApproved( uint256 _tokenId ) external view onlyValidToken(_tokenId) returns (address) { return approvedTransfers[_tokenId]; } /** * Check whether an address is an authorized operator of another address. * * Parameters * ---------- * _owner : address * The address of which to check whether it has approved the other * address to act as operator. * _operator : address * The address of which to check whether it has been approved to act * as operator on behalf of `_owner`. * * Returns * ------- * bool * True if `_operator` is approved for all actions on behalf of * `_owner`. * * Notice * ------ * This method cannot fail, as the Ethereum network guarantees that all * address mappings exist and are set to the zero address by default. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool) { return operators[_owner][_operator]; } /** * Get the total number of tokens currently in circulation. * * Returns * ------- * uint256 * The total number of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return totalTokens; } /** * Get token identifier by index. * * Parameters * ---------- * _index : uint256 * The index of the token to get the identifier of. * * Returns * ------- * uint256 * The identifier of the token at given index. * * Notice * ------ * Ethergotchi tokens are incrementally numbered starting from zero, and * always go up by one. The index of the token is thus equivalent to its * identifier. */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalTokens); return _index; } /** * Get token of owner by index. * * Parameters * ---------- * _owner : address * The address of the owner of which to get the token of. * _index : uint256 * The index of the token in the given owner"s list of token. * * Returns * ------- * uint256 * The identifier of the token at given index of an owner"s list of * tokens. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256) { require(_index < tokenIdsByOwner[_owner].length); return tokenIdsByOwner[_owner][_index]; } /** * Check whether given address is a smart contract. * * Parameters * ---------- * _address : address * The address of which to check whether it is a contract. * * Returns * ------- * bool * True if given address is a contract, else False. * * Notice * ------ * This method works as long as the `Serenity` update of Ethereum has not * been deployed. At the time of writing, contracts cannot set their code * size to zero, nor can "normal" addresses set their code size to anything * non-zero. With `Serenity` the idea will be that each and every address * is an contract, effectively rendering this method. */ function _isContract(address _address) internal view returns (bool) { uint size; assembly { size := extcodesize(_address) } return size > 0; } /** * Transfer the ownership of given token from one address to another. * * Parameters * ---------- * _from : address * The benefactor address to transfer the given token from. * _to : address * The beneficiary address to transfer the given token to. * _tokenId : uint256 * The identifier of the token to transfer. * data : bytes * Non-specified data to send along the transfer towards the `to` * address that can be processed. * * Notice * ------ * This method performs a check to determine whether the receiving party is * a smart contract by calling the `_isContract` method. This works until * the `Serenity` update of Ethereum is deployed. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes data ) internal onlyValidTransfers(_from, _to, _tokenId) { // Call the method that performs the actual transfer. All common cases // of "wrong" transfers have already been checked at this point. The // internal transfer method does no checking. _transfer(_to, _tokenId); // Check whether the receiving party is a contract, and if so, call // the `onERC721Received` method as defined in the ERC-721 standard. if (_isContract(_to)) { // Assume the receiving party has implemented ERC721TokenReceiver, // as otherwise the "unsafe" `transferFrom` method should have been // called instead. ERC721TokenReceiver _receiver = ERC721TokenReceiver(_to); // The response returned by `onERC721Received` of the receiving // contract"s `on *must* be equal to the magic number defined by // the ERC-165 signature of `ERC721TokenReceiver`. If this is not // the case, the transaction will be reverted. require( _receiver.onERC721Received( address(this), _tokenId, data ) == INTERFACE_SIGNATURE_ERC721_TOKEN_RECEIVER ); } } /** * Transfer token to new owner. * * Parameters * ---------- * _to : address * The address of the owner-to-be of given token. * _tokenId : _tokenId * The identifier of the token that is to be transferred. * * Notice * ------ * This method performs no safety checks as it can only be called within * the controlled environment of this contract. */ function _transfer(address _to, uint256 _tokenId) internal { // Get current owner of the token. It is technically possible that the // owner is the same address as the address to which the token is to be // sent to. In this case the token will be moved to the end of the list // of tokens owned by this address. address _from = ownerByTokenId[_tokenId]; // There are two possible scenarios for transfers when it comes to the // removal of the token from the side that currently owns the token: // 1: the owner has two or more tokens; or // 2: the owner has one token. if (tokenIdsByOwner[_from].length > 1) { // Get the index of the token that has to be removed from the list // of tokens owned by the current owner. uint256 tokenIndexToDelete = ownerTokenIndexByTokenId[_tokenId]; // To keep the list of tokens without gaps, and thus reducing the // gas cost associated with interacting with the list, the last // token in the owner"s list of tokens is moved to fill the gap // created by removing the token. uint256 tokenIndexToMove = tokenIdsByOwner[_from].length - 1; // Overwrite the token that is to be removed with the token that // was at the end of the list. It is possible that both are one and // the same, in which case nothing happens. tokenIdsByOwner[_from][tokenIndexToDelete] = tokenIdsByOwner[_from][tokenIndexToMove]; } // Remove the last item in the list of tokens owned by the current // owner. This item has either already been copied to the location of // the token that is to be transferred, or is the only token of this // owner in which case the list of tokens owned by this owner is now // empty. tokenIdsByOwner[_from].length--; // Add the token to the list of tokens owned by `_to`. Items are always // added to the very end of the list. This makes the token index of the // new token within the owner"s list of tokens equal to the length of // the list minus one as Solidity is a zero-based language. This token // index is then set for this token identifier. tokenIdsByOwner[_to].push(_tokenId); ownerTokenIndexByTokenId[_tokenId] = tokenIdsByOwner[_to].length - 1; // Set the direct ownership information of the token to the new owner // after all other ownership-related mappings have been updated to make // sure the "side" data is correct. ownerByTokenId[_tokenId] = _to; // Remove the approved address of this token. It may be the case there // was no approved address, in which case nothing changes. approvedTransfers[_tokenId] = address(0); // Log the transfer event onto the blockchain to leave behind an audit // trail of all transfers that have taken place. Transfer(_from, _to, _tokenId); } /** * Add new token into circulation. * * Parameters * ---------- * _tokenId : uint256 * The identifier of the token to add into circulation. * _owner : address * The address of the owner who receives the newly added token. */ function _add(uint256 _tokenId, address _owner) internal { // Ensure the token does not already exist, and prevent duplicate calls // using the same identifier. require(ownerByTokenId[_tokenId] == address(0)); // Update the direct ownership mapping, by setting the owner of the // token identifier to `_owner`, and adding the token to the list of // tokens owned by `_owner`. Arrays are always initialized to empty // versions of of their specific type, thus ensuring that the `push` // method will not fail. ownerByTokenId[_tokenId] = _owner; tokenIdsByOwner[_owner].push(_tokenId); // Update the mapping that keeps track of a token"s index within the // list of tokens owned by each owner. At the time of addition a token // is always added to the end of the list, and will thus always equal // the number of tokens already in the list, minus one, because the // arrays within Solidity are zero-based. ownerTokenIndexByTokenId[_tokenId] = tokenIdsByOwner[_owner].length - 1; totalTokens += 1; } /*********************************************/ /** MIGRATION state variables and functions **/ /*********************************************/ // This number is used to keep track of how many tokens have been migrated. // The number cannot exceed the number of tokens that were assigned to // owners in the previous Ownership contract. uint256 public migrationIndex; // The previous token ownership contract. PartialOwnership private formerContract; /** * Migrate data from the former Ethergotchi ownership contract. * * Parameters * ---------- * _count : uint256 * The number of tokens to migrate in a single transaction. * * Notice * ------ * This method is limited in use to ensure no 'malicious' calls are made. * Additionally, this method writes to a contract state variable to keep * track of how many tokens have been migrated. */ function migrate(uint256 _count) external onlyOwner { // Ensure that the migrate function can *only* be called in a specific // time period. This period ranges from Saturday, March 24th, 00:00:00 // UTC until Sunday, March 25th, 23:59:59 UTC. require(1521849600 <= now && now <= 1522022399); // Get the maximum number of tokens handed out by the previous // ownership contract. uint256 formerTokenCount = formerContract.totalSupply(); // The index to stop the migration at for this transaction. uint256 endIndex = migrationIndex + _count; // It is possible that the final transaction has a higher end index // than there are a number of tokens. In this case, the end index is // reduced to ensure no non-existent tokens are migrated. if (endIndex >= formerTokenCount) { endIndex = formerTokenCount; } // Loop through the token identifiers to migrate in this transaction. // Token identifiers are equivalent to their 'index', as identifiers // start at zero (with the zeroth token being owned by the zero // address), and are incremented by one for each new token. for (uint256 i = migrationIndex; i < endIndex; i++) { address tokenOwner; // There was a malicious account that acquired over 400 eggs via // referral codes, which breaks the terms of use. The acquired egg // numbers ranged from identifier 1247 up until 1688, excluding // 1296, 1297, 1479, 1492, 1550, 1551, and 1555. This was found by // looking at activity on the pick-up contract, and tracing it back // to the following address: // `0c7a911ac29ea1e3b1d438f98f8bc053131dcaf52` if (_isExcluded(i)) { tokenOwner = address(0); } else { tokenOwner = formerContract.ownerOf(i); } // Assign the token to the same address that owned it in the // previous ownership contract. _add(i, tokenOwner); // Log the token transfer. In this case where the token is 'newly' // created, but actually transferred from a previous contract, the // `_from` address is set to the previous contract address, to // signify a migration. Transfer(address(formerContract), tokenOwner, i); } // Set the new migration index to where the current transaction ended // its migration. migrationIndex = endIndex; } /** * Check if Ethergotchi should be excluded from migration. * * Parameters * ---------- * _gotchiId : uint256 * The identifier of the Ethergotchi of which to check the exclusion * status. * * Returns * ------- * bool * True if the Ethergotchi should be excluded from the migration, else * False. */ function _isExcluded(uint256 _gotchiId) internal pure returns (bool) { return 1247 <= _gotchiId && _gotchiId <= 1688 && _gotchiId != 1296 && _gotchiId != 1297 && _gotchiId != 1479 && _gotchiId != 1492 && _gotchiId != 1550 && _gotchiId != 1551 && _gotchiId != 1555; } }
* Modify method to only allow calls if the token is valid. Notice ------ Ethergotchi are valid if they are owned by an address that is not the zero address./
modifier onlyValidToken(uint256 _tokenId) { require(ownerByTokenId[_tokenId] != address(0)); _; }
12,544,590
[ 1, 11047, 707, 358, 1338, 1699, 4097, 309, 326, 1147, 353, 923, 18, 24914, 31913, 512, 1136, 13212, 24010, 854, 923, 309, 2898, 854, 16199, 635, 392, 1758, 716, 353, 486, 326, 3634, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 9606, 1338, 1556, 1345, 12, 11890, 5034, 389, 2316, 548, 13, 288, 203, 3639, 2583, 12, 8443, 858, 1345, 548, 63, 67, 2316, 548, 65, 480, 1758, 12, 20, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Gauge interface Gauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function claim_rewards() external; function claimable_reward(address, address) external view returns (uint256); function withdraw(uint256) external; } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // stETH pool uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function balances(int128) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); function calc_token_amount( uint256[2] calldata amounts, bool is_deposit) external view returns (uint256); } // Part: IMooniswap interface IMooniswap { function swap(address src, address dst, uint256 amount, uint256 minReturn, address referral) external payable returns(uint256 result); } // Part: IStrategyProxy interface IStrategyProxy { function withdraw( address _gauge, address _token, uint256 _amount ) external returns (uint256); function balanceOf(address _gauge) external view returns (uint256); function withdrawAll(address _gauge, address _token) external returns (uint256); function deposit(address _gauge, address _token) external; function harvest(address _gauge) external; function lock() external; function claimRewards(address _gauge, address _token) external; function approveStrategy(address _gauge, address _strategy) external; } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { 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 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); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: ICrvV3 interface ICrvV3 is IERC20 { function minter() external view returns (address); } // Part: ISteth interface ISteth is IERC20 { function submit(address) external payable returns (uint256); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { 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; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol // Import interfaces for many popular DeFi projects, or add your own! //import "../interfaces/<protocol>/<Interface>.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address private uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private sushiswapRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private mooniswappool = 0x1f629794B34FFb3B29FF206Be5478A52678b47ae; address private referal = 0xC3D6880fD95E06C816cB030fAc45b3ffe3651Cb0; address public constant gauge = address(0x182B723a58739a9c974cFDB385ceaDb237453c28); address public voter = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); // Yearn's veCRV voter address public ldoRouter = 0x1f629794B34FFb3B29FF206Be5478A52678b47ae; address[] public ldoPath; address public crvRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address[] public crvPath; uint256 public keepCrvPercent = 1000; // over keepCrvDenominator uint256 public constant keepCrvDenominator = 10000; bool public checkLiqGauge = true; ICurveFi public StableSwapSTETH = ICurveFi(address(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022)); // IMinter public CrvMinter = IMinter(address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0)); //IStrategyProxy public proxy = IStrategyProxy(address(0x9a3a03C614dc467ACC3e81275468e033c98d960E)); IStrategyProxy public proxy = IStrategyProxy(address(0x9a165622a744C20E3B2CB443AeD98110a33a231b)); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ISteth public stETH = ISteth(address(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84)); IERC20 public LDO = IERC20(address(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32)); ICrvV3 public CRV = ICrvV3(address(0xD533a949740bb3306d119CC777fa900bA034cd52)); constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want maxReportDelay = 43200; profitFactor = 2000; debtThreshold = 400*1e18; stETH.approve(address(StableSwapSTETH), uint256(-1)); LDO.safeApprove(ldoRouter, uint256(-1)); CRV.approve(crvRouter, uint256(-1)); ldoPath = new address[](2); ldoPath[0] = address(LDO); ldoPath[1] = weth; crvPath = new address[](2); crvPath[0] = address(CRV); crvPath[1] = weth; } //we get eth receive() external payable {} // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ //0 uniswap, 1 sushi, 2 inch function setLDORouter(uint256 exchange, address[] calldata _path) public onlyGovernance { if(exchange == 0){ ldoRouter = uniswapRouter; }else if (exchange == 1) { ldoRouter = sushiswapRouter; }else if (exchange == 2) { ldoRouter = mooniswappool; }else{ require(false, "incorrect pool"); } ldoPath = _path; LDO.safeApprove(ldoRouter, uint256(-1)); } function updateMooniswapPoolAddress(address newAddress) public onlyGovernance { mooniswappool = newAddress; } function updateReferal(address _referal) public onlyAuthorized { referal = _referal; } function updateCheckLiqGauge(bool _checkLiqGauge) public onlyAuthorized { checkLiqGauge = _checkLiqGauge; } function setCRVRouter(uint256 exchange, address[] calldata _path) public onlyGovernance { if(exchange == 0){ crvRouter = uniswapRouter; }else if (exchange == 1) { crvRouter = sushiswapRouter; }else{ require(false, "incorrect pool"); } crvPath = _path; CRV.approve(crvRouter, uint256(-1)); } function setProxy(address _proxy) external onlyGovernance { proxy = IStrategyProxy(_proxy); } function setVoter(address _voter) external onlyGovernance { voter = _voter; } function name() external override view returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "StrategystETHCurve"; } function estimatedTotalAssets() public override view returns (uint256) { return proxy.balanceOf(gauge).add(want.balanceOf(address(this))); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // TODO: Do stuff here to free up any returns back into `want` // NOTE: Return `_profit` which is value generated by all positions, priced in `want` // NOTE: Should try to free up at least `_debtOutstanding` of underlying position uint256 gaugeTokens = proxy.balanceOf(gauge); if(gaugeTokens > 0){ proxy.harvest(gauge); proxy.claimRewards(gauge, address(LDO)); uint256 ldo_balance = LDO.balanceOf(address(this)); if(ldo_balance > 0){ _sell(address(LDO), ldo_balance); } uint256 crvBalance = CRV.balanceOf(address(this)); if(crvBalance > 0){ uint256 keepCrv = crvBalance.mul(keepCrvPercent).div(keepCrvDenominator); IERC20(address(CRV)).safeTransfer(voter, keepCrv); proxy.lock(); crvBalance = crvBalance.sub(keepCrv); _sell(address(CRV), crvBalance); } uint256 balance = address(this).balance; uint256 balance2 = stETH.balanceOf(address(this)); if(balance > 0 || balance2 > 0){ StableSwapSTETH.add_liquidity{value: balance}([balance, balance2], 0); } _profit = want.balanceOf(address(this)); } if(_debtOutstanding > 0){ uint256 stakedBal = proxy.balanceOf(gauge); proxy.withdraw(gauge, address(want), Math.min(stakedBal, _debtOutstanding)); _debtPayment = Math.min(_debtOutstanding, want.balanceOf(address(this))); } } function adjustPosition(uint256 _debtOutstanding) internal override { //when migrated to we will sometimes have liquidity guage balance. //this should be withdrawn and added to proxy if(checkLiqGauge){ uint256 liqGaugeBal = Gauge(gauge).balanceOf(address(this)); if(liqGaugeBal > 0){ Gauge(gauge).withdraw(liqGaugeBal); } } uint256 _toInvest = want.balanceOf(address(this)); want.safeTransfer(address(proxy), _toInvest); proxy.deposit(gauge, address(want)); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBal = want.balanceOf(address(this)); uint256 stakedBal = proxy.balanceOf(gauge); if(_amountNeeded > wantBal){ proxy.withdraw(gauge, address(want), Math.min(stakedBal, _amountNeeded - wantBal)); } _liquidatedAmount = Math.min(_amountNeeded, want.balanceOf(address(this))); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { uint256 gaugeTokens = proxy.balanceOf(gauge); if (gaugeTokens > 0) { proxy.withdraw(gauge, address(want), gaugeTokens); } } //sell all function function _sell(address currency, uint256 amount) internal { if(currency == address(LDO)){ if(ldoRouter == mooniswappool){ //we sell to stETH IMooniswap(mooniswappool).swap(currency, address(stETH), amount, 1, referal); }else{ IUniswapV2Router02(ldoRouter).swapExactTokensForETH(amount, uint256(0), ldoPath, address(this), now); } } else if(currency == address(CRV)){ IUniswapV2Router02(crvRouter).swapExactTokensForETH(amount, uint256(0), crvPath, address(this), now); }else{ require(false, "BAD SELL"); } } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = gauge; return protected; } }
Override this to add all tokens/tokenized positions this contract manages on a *persistent* basis (e.g. not just for swapping back to want ephemerally) NOTE: Do *not* include `want`, already included in `sweep` below Example: function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = tokenA; protected[1] = tokenB; protected[2] = tokenC; return protected; }
function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = gauge; return protected; }
14,009,933
[ 1, 6618, 333, 358, 527, 777, 2430, 19, 2316, 1235, 6865, 333, 6835, 20754, 281, 603, 279, 9195, 10853, 261, 73, 18, 75, 18, 486, 2537, 364, 7720, 1382, 1473, 358, 2545, 425, 12549, 264, 1230, 13, 5219, 30, 2256, 486, 2341, 1375, 17369, 9191, 1818, 5849, 316, 1375, 87, 25236, 68, 5712, 5090, 30, 565, 445, 4750, 5157, 1435, 2713, 3849, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 1377, 1758, 8526, 3778, 4750, 273, 394, 1758, 8526, 12, 23, 1769, 1377, 4750, 63, 20, 65, 273, 1147, 37, 31, 1377, 4750, 63, 21, 65, 273, 1147, 38, 31, 1377, 4750, 63, 22, 65, 273, 1147, 39, 31, 1377, 327, 4750, 31, 565, 289, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4750, 5157, 1435, 203, 3639, 2713, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8526, 3778, 13, 203, 565, 288, 203, 203, 3639, 1758, 8526, 3778, 4750, 273, 394, 1758, 8526, 12, 21, 1769, 203, 1850, 4750, 63, 20, 65, 273, 13335, 31, 203, 377, 203, 1850, 327, 4750, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8Cba9816E49Ee0a2e6611Cf3ab81b195AD9C5514/sources/contracts/gemSwap/Atomicizer.sol
execute trades return remaining ETH (if any)
function batchBuyWithETH(MarketRegistry.TradeDetails[] memory tradeDetails) external payable nonReentrant { _trade(tradeDetails); assembly { if gt(selfbalance(), 0) { let callStatus := call( gas(), caller(), selfbalance(), 0, 0, 0, 0 ) } } }
4,824,500
[ 1, 8837, 1284, 5489, 327, 4463, 512, 2455, 261, 430, 1281, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2581, 38, 9835, 1190, 1584, 44, 12, 3882, 278, 4243, 18, 22583, 3790, 8526, 3778, 18542, 3790, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 389, 20077, 12, 20077, 3790, 1769, 203, 203, 3639, 19931, 288, 203, 5411, 309, 9879, 12, 2890, 12296, 9334, 374, 13, 288, 203, 7734, 2231, 745, 1482, 519, 745, 12, 203, 10792, 16189, 9334, 203, 10792, 4894, 9334, 203, 10792, 365, 12296, 9334, 203, 10792, 374, 16, 203, 10792, 374, 16, 203, 10792, 374, 16, 203, 10792, 374, 203, 7734, 262, 203, 5411, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // Contracts import { PausableMods } from "../settings/pausable/PausableMods.sol"; import { ReentryMods } from "../contexts2/access-control/reentry/ReentryMods.sol"; import { RolesMods } from "../contexts2/access-control/roles/RolesMods.sol"; import { AUTHORIZED } from "../shared/roles.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Libraries import { LibLoans } from "./libraries/LibLoans.sol"; import { LibEscrow } from "../escrow/libraries/LibEscrow.sol"; import { LibCollateral } from "./libraries/LibCollateral.sol"; import { LibConsensus } from "./libraries/LibConsensus.sol"; import { LendingLib } from "../lending/libraries/LendingLib.sol"; import { PlatformSettingsLib } from "../settings/platform/libraries/PlatformSettingsLib.sol"; import { MaxDebtRatioLib } from "../settings/asset/libraries/MaxDebtRatioLib.sol"; import { MaxLoanAmountLib } from "../settings/asset/libraries/MaxLoanAmountLib.sol"; import { Counters } from "@openzeppelin/contracts/utils/Counters.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { NumbersLib } from "../shared/libraries/NumbersLib.sol"; import { NFTLib, NftLoanSizeProof } from "../nft/libraries/NFTLib.sol"; // Interfaces import { ILoansEscrow } from "../escrow/escrow/ILoansEscrow.sol"; // Proxy import { BeaconProxy } from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol"; // Storage import { LoanRequest, LoanResponse, LoanStatus, LoanTerms, Loan, MarketStorageLib } from "../storage/market.sol"; import { AppStorageLib } from "../storage/app.sol"; contract CreateLoanFacet is RolesMods, ReentryMods, PausableMods { /** * @notice This event is emitted when loan terms have been successfully set * @param loanID ID of loan from which collateral was withdrawn * @param borrower Account address of the borrower */ event LoanTermsSet(uint256 indexed loanID, address indexed borrower); /** * @notice This event is emitted when a loan has been successfully taken out * @param loanID ID of loan from which collateral was withdrawn * @param borrower Account address of the borrower * @param amountBorrowed Total amount taken out in the loan * @param withNFT Boolean indicating if the loan was taken out using NFTs */ event LoanTakenOut( uint256 indexed loanID, address indexed borrower, uint256 amountBorrowed, bool withNFT ); /** * @notice Creates a loan with the loan request and terms * @param request Struct of the protocol loan request * @param responses List of structs of the protocol loan responses * @param collateralToken Token address to use as collateral for the new loan * @param collateralAmount Amount of collateral required for the loan */ function createLoanWithTerms( LoanRequest calldata request, LoanResponse[] calldata responses, address collateralToken, uint256 collateralAmount ) external payable paused(LibLoans.ID, false) nonReentry("") authorized(AUTHORIZED, msg.sender) { CreateLoanLib.verifyCreateLoan(request, collateralToken); uint256 loanID = CreateLoanLib.initLoan(request, responses, collateralToken); // Pay in collateral if (collateralAmount > 0) { LibCollateral.deposit(loanID, collateralAmount); } emit LoanTermsSet(loanID, msg.sender); } function takeOutLoanWithNFTs( uint256 loanID, uint256 amount, NftLoanSizeProof[] calldata proofs ) external paused(LibLoans.ID, false) __takeOutLoan(loanID, amount) { // Set the collateral ratio to 0 as linked NFTs are used as the collateral LibLoans.loan(loanID).collateralRatio = 0; uint256 allowedLoanSize; for (uint256 i; i < proofs.length; i++) { NFTLib.applyToLoan(loanID, proofs[i]); allowedLoanSize += proofs[i].baseLoanSize; if (allowedLoanSize >= amount) { break; } } require( amount <= allowedLoanSize, "Teller: insufficient NFT loan size" ); // Pull funds from Teller Token LP and transfer to the new loan escrow LendingLib.tToken(LibLoans.loan(loanID).lendingToken).fundLoan( CreateLoanLib.createEscrow(loanID), amount ); emit LoanTakenOut(loanID, msg.sender, amount, true); } modifier __takeOutLoan(uint256 loanID, uint256 amount) { Loan storage loan = LibLoans.loan(loanID); require(msg.sender == loan.borrower, "Teller: not borrower"); require(loan.status == LoanStatus.TermsSet, "Teller: loan not set"); require( uint256(LibLoans.terms(loanID).termsExpiry) >= block.timestamp, "Teller: loan terms expired" ); require( LendingLib.tToken(loan.lendingToken).debtRatioFor(amount) <= MaxDebtRatioLib.get(loan.lendingToken), "Teller: max supply-to-debt ratio exceeded" ); require( LibLoans.terms(loanID).maxLoanAmount >= amount, "Teller: max loan amount exceeded" ); loan.borrowedAmount = amount; LibLoans.debt(loanID).principalOwed = amount; LibLoans.debt(loanID).interestOwed = LibLoans.getInterestOwedFor( uint256(loan.id), amount ); loan.status = LoanStatus.Active; loan.loanStartTime = uint32(block.timestamp); _; } /** * @notice Take out a loan * * @dev collateral ratio is a percentage of the loan amount that's required in collateral * @dev the percentage will be *(10**2). I.e. collateralRatio of 5244 means 52.44% collateral * @dev is required in the loan. Interest rate is also a percentage with 2 decimal points. */ function takeOutLoan(uint256 loanID, uint256 amount) external paused(LibLoans.ID, false) nonReentry("") authorized(AUTHORIZED, msg.sender) __takeOutLoan(loanID, amount) { { // Check that enough collateral has been provided for this loan (, uint256 neededInCollateral, ) = LibLoans.getCollateralNeededInfo(loanID); require( neededInCollateral <= LibCollateral.e(loanID).loanSupply(loanID), "Teller: more collateral required" ); } Loan storage loan = MarketStorageLib.store().loans[loanID]; address loanRecipient; bool eoaAllowed = LibLoans.canGoToEOAWithCollateralRatio(loan.collateralRatio); if (eoaAllowed) { loanRecipient = loan.borrower; } else { loanRecipient = CreateLoanLib.createEscrow(loanID); } // Pull funds from Teller token LP and and transfer to the recipient LendingLib.tToken(LibLoans.loan(loanID).lendingToken).fundLoan( loanRecipient, amount ); emit LoanTakenOut(loanID, msg.sender, amount, false); } } library CreateLoanLib { function verifyCreateLoan( LoanRequest calldata request, address collateralToken ) internal view { // Perform loan request checks require(msg.sender == request.borrower, "Teller: not loan requester"); require( PlatformSettingsLib.getMaximumLoanDurationValue() >= request.duration, "Teller: max loan duration exceeded" ); // Verify collateral token is acceptable require( EnumerableSet.contains( MarketStorageLib.store().collateralTokens[request.assetAddress], collateralToken ), "Teller: collateral token not allowed" ); require( MaxLoanAmountLib.get(request.assetAddress) > request.amount, "Teller: asset max loan amount exceeded" ); } function initLoan( LoanRequest calldata request, LoanResponse[] calldata responses, address collateralToken ) internal returns (uint256 loanID_) { // Get consensus values from request (uint16 interestRate, uint16 collateralRatio, uint256 maxLoanAmount) = LibConsensus.processLoanTerms(request, responses); // Get and increment new loan ID loanID_ = CreateLoanLib.newID(); LibLoans.terms(loanID_).maxLoanAmount = maxLoanAmount; LibLoans.terms(loanID_).termsExpiry = uint32( block.timestamp + PlatformSettingsLib.getTermsExpiryTimeValue() ); LibLoans.loan(loanID_).id = uint128(loanID_); LibLoans.loan(loanID_).status = LoanStatus.TermsSet; LibLoans.loan(loanID_).lendingToken = request.assetAddress; LibLoans.loan(loanID_).collateralToken = collateralToken; LibLoans.loan(loanID_).borrower = request.borrower; LibLoans.loan(loanID_).interestRate = interestRate; LibLoans.loan(loanID_).collateralRatio = collateralRatio; LibLoans.loan(loanID_).duration = request.duration; // Add loanID to borrower list MarketStorageLib.store().borrowerLoans[request.borrower].push( uint128(loanID_) ); } function newID() internal returns (uint256 id_) { Counters.Counter storage counter = MarketStorageLib.store().loanIDCounter; id_ = Counters.current(counter); Counters.increment(counter); } function createEscrow(uint256 loanID) internal returns (address escrow_) { // Create escrow escrow_ = AppStorageLib.store().loansEscrowBeacon.cloneProxy(""); ILoansEscrow(escrow_).init(); // Save escrow address for loan MarketStorageLib.store().loanEscrows[loanID] = ILoansEscrow(escrow_); } }
* @notice This event is emitted when loan terms have been successfully set @param loanID ID of loan from which collateral was withdrawn @param borrower Account address of the borrower/* @notice This event is emitted when a loan has been successfully taken out @param loanID ID of loan from which collateral was withdrawn @param borrower Account address of the borrower @param amountBorrowed Total amount taken out in the loan @param withNFT Boolean indicating if the loan was taken out using NFTs/* @notice Creates a loan with the loan request and terms @param request Struct of the protocol loan request @param responses List of structs of the protocol loan responses @param collateralToken Token address to use as collateral for the new loan @param collateralAmount Amount of collateral required for the loan/ Pay in collateral
{ CreateLoanLib.verifyCreateLoan(request, collateralToken); uint256 loanID = CreateLoanLib.initLoan(request, responses, collateralToken); if (collateralAmount > 0) { LibCollateral.deposit(loanID, collateralAmount); } emit LoanTermsSet(loanID, msg.sender); }
12,730,847
[ 1, 2503, 871, 353, 17826, 1347, 28183, 6548, 1240, 2118, 4985, 444, 225, 28183, 734, 1599, 434, 28183, 628, 1492, 4508, 2045, 287, 1703, 598, 9446, 82, 225, 29759, 264, 6590, 1758, 434, 326, 29759, 264, 19, 225, 1220, 871, 353, 17826, 1347, 279, 28183, 711, 2118, 4985, 9830, 596, 225, 28183, 734, 1599, 434, 28183, 628, 1492, 4508, 2045, 287, 1703, 598, 9446, 82, 225, 29759, 264, 6590, 1758, 434, 326, 29759, 264, 225, 3844, 38, 15318, 329, 10710, 3844, 9830, 596, 316, 326, 28183, 225, 598, 50, 4464, 3411, 11193, 309, 326, 28183, 1703, 9830, 596, 1450, 423, 4464, 87, 19, 225, 10210, 279, 28183, 598, 326, 28183, 590, 471, 6548, 225, 590, 7362, 434, 326, 1771, 28183, 590, 225, 7220, 987, 434, 8179, 434, 326, 1771, 28183, 7220, 225, 4508, 2045, 287, 1345, 3155, 1758, 358, 999, 487, 4508, 2045, 287, 364, 326, 394, 28183, 225, 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, 1788, 1504, 304, 5664, 18, 8705, 1684, 1504, 304, 12, 2293, 16, 4508, 2045, 287, 1345, 1769, 203, 3639, 2254, 5034, 28183, 734, 273, 203, 5411, 1788, 1504, 304, 5664, 18, 2738, 1504, 304, 12, 2293, 16, 7220, 16, 4508, 2045, 287, 1345, 1769, 203, 203, 3639, 309, 261, 12910, 2045, 287, 6275, 405, 374, 13, 288, 203, 5411, 10560, 13535, 2045, 287, 18, 323, 1724, 12, 383, 304, 734, 16, 4508, 2045, 287, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 3176, 304, 11673, 694, 12, 383, 304, 734, 16, 1234, 18, 15330, 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 ]
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Bridge.sol
@notice Allows to defeat a pending fraud challenge against a wallet if the transaction that spends the UTXO follows the protocol rules. In order to defeat the challenge the same `walletPublicKey` and signature (represented by `r`, `s` and `v`) must be provided as were used to calculate the sighash during input signing. The fraud challenge defeat attempt will only succeed if the inputs in the preimage are considered honestly spent by the wallet. Therefore the transaction spending the UTXO must be proven in the Bridge before a challenge defeat is called. If successfully defeated, the fraud challenge is marked as resolved and the amount of ether deposited by the challenger is sent to the treasury. @param walletPublicKey The public key of the wallet in the uncompressed and unprefixed format (64 bytes). @param preimage The preimage which produces sighash used to generate the ECDSA signature that is the subject of the fraud claim. It is a serialized subset of the transaction. The exact subset used as the preimage depends on the transaction input the signature is produced for. See BIP-143 for reference. @param witness Flag indicating whether the preimage was produced for a witness input. True for witness, false for non-witness input. @dev Requirements: - `walletPublicKey` and `sighash` calculated as `hash256(preimage)` must identify an open fraud challenge, - the preimage must be a valid preimage of a transaction generated according to the protocol rules and already proved in the Bridge, - before a defeat attempt is made the transaction that spends the given UTXO must be proven in the Bridge.
function defeatFraudChallenge( bytes calldata walletPublicKey, bytes calldata preimage, bool witness ) external { self.defeatFraudChallenge(walletPublicKey, preimage, witness); }
4,856,485
[ 1, 19132, 358, 1652, 73, 270, 279, 4634, 284, 354, 1100, 12948, 5314, 279, 9230, 309, 540, 326, 2492, 716, 17571, 87, 326, 4732, 60, 51, 13040, 326, 1771, 2931, 18, 540, 657, 1353, 358, 1652, 73, 270, 326, 12948, 326, 1967, 1375, 19177, 9632, 68, 471, 540, 3372, 261, 28205, 329, 635, 1375, 86, 9191, 1375, 87, 68, 471, 1375, 90, 24065, 1297, 506, 2112, 487, 540, 4591, 1399, 358, 4604, 326, 272, 2031, 961, 4982, 810, 10611, 18, 540, 1021, 284, 354, 1100, 12948, 1652, 73, 270, 4395, 903, 1338, 12897, 309, 326, 540, 4540, 316, 326, 675, 2730, 854, 7399, 24338, 395, 715, 26515, 635, 326, 540, 9230, 18, 17189, 326, 2492, 272, 9561, 326, 4732, 60, 51, 1297, 506, 540, 450, 3995, 316, 326, 24219, 1865, 279, 12948, 1652, 73, 270, 353, 2566, 18, 540, 971, 4985, 1652, 73, 690, 16, 326, 284, 354, 1100, 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, 1652, 73, 270, 42, 354, 1100, 18359, 12, 203, 3639, 1731, 745, 892, 9230, 9632, 16, 203, 3639, 1731, 745, 892, 675, 2730, 16, 203, 3639, 1426, 15628, 203, 565, 262, 3903, 288, 203, 3639, 365, 18, 536, 73, 270, 42, 354, 1100, 18359, 12, 19177, 9632, 16, 675, 2730, 16, 15628, 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 ]
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: openzeppelin-solidity/contracts/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 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/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) internal balances; uint256 internal 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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/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: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/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 OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @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 hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: contracts/WhiteListManager.sol contract WhiteListManager is Ownable { // The list here will be updated by multiple separate WhiteList contracts mapping (address => bool) public list; function greylist(address addr) public onlyOwner { list[addr] = false; } function greylistMany(address[] addrList) public onlyOwner { for (uint256 i = 0; i < addrList.length; i++) { greylist(addrList[i]); } } function whitelist(address addr) public onlyOwner { list[addr] = true; } function whitelistMany(address[] addrList) public onlyOwner { for (uint256 i = 0; i < addrList.length; i++) { whitelist(addrList[i]); } } function isWhitelisted(address addr) public view returns (bool) { return list[addr]; } } // File: contracts/Token.sol contract MedipediaToken is MintableToken, BurnableToken, DetailedERC20, WhiteListManager{ // ------------------------------------------------------------------------ // Every token amount must be multiplied by constant E18 to reflect decimals // ------------------------------------------------------------------------ uint256 constant E18 = 10**18; uint256 public constant BUSINESS_DEVELOPMENT_SUPPLY_LIMIT = 520000000 * E18; // 520,000,000 tokens uint256 public constant MANAGEMENT_TEAM_SUPPLY_LIMIT = 520000000 * E18; // 520,000,000 tokens will be Locked for 18 Months uint256 public constant ADVISORS_SUPPLY_LIMIT = 130000000 * E18; // 130,000,000 tokens will be Locked for 12 Months uint256 public constant EARLY_INVESTORS_SUPPLY_LIMIT = 130000000 * E18; // 130,000,000 tokens will be Locked for 12 Months // ------------------------------------------------------------------------ // INITIAL_SUPPLY = BUSINESS_DEVELOPMENT_SUPPLY_LIMIT + MANAGEMENT_TEAM_SUPPLY_LIMIT + // ADVISORS_SUPPLY_LIMIT + EARLY_INVESTORS_SUPPLY_LIMIT // ------------------------------------------------------------------------ uint256 public constant INITIAL_SUPPLY = 1300000000 * E18;// 1.3 Billion tokens uint256 public constant TOTAL_SUPPLY_LIMIT = 2600000000 * E18;// 2.6 Billion tokens uint256 public constant TOKEN_SUPPLY_AIRDROP_LIMIT = 15000000 * E18; // 15,000,000 tokens uint256 public constant TOKEN_SUPPLY_BOUNTY_LIMIT = 35000000 * E18; // 35,000,000 tokens uint256 totalTokensIssuedToAdvisor; uint256 totalTokensIssuedToEarlyInvestors; uint256 totalTokensIssuedToMgmtTeam; uint256 releaseTimeToUnlockAdvisorTokens; uint256 releaseTimeToUnlockEarlyInvestorTokens; uint256 releaseTimeToUnlockManagementTokens; bool public isICORunning; address public icoContract; uint256 public airDropTokenIssuedTotal; uint256 public bountyTokenIssuedTotal; uint256 public preICOTokenIssuedTotal; uint8 private constant AIRDROP_EVENT = 1; uint8 private constant BOUNTY_EVENT = 2; uint8 private constant PREICO_EVENT = 3; uint8 private constant ICO_EVENT = 4; event Released(uint256 amount); constructor(string _name, string _symbol, uint8 _decimals) DetailedERC20(_name, _symbol, _decimals) public { balances[msg.sender] = BUSINESS_DEVELOPMENT_SUPPLY_LIMIT; totalSupply_ = INITIAL_SUPPLY; totalTokensIssuedToAdvisor = 0; totalTokensIssuedToEarlyInvestors = 0; totalTokensIssuedToMgmtTeam = 0; airDropTokenIssuedTotal = 0; bountyTokenIssuedTotal = 0; preICOTokenIssuedTotal = 0; //Epoch timestamps releaseTimeToUnlockAdvisorTokens = 1566345600; // GMT: Wednesday, 21 August 2019 00:00:00 releaseTimeToUnlockEarlyInvestorTokens = 1566345600; // GMT: Wednesday, 21 August 2019 00:00:00 releaseTimeToUnlockManagementTokens = 1582243200; // GMT: Friday, 21 February 2020 00:00:00 } // ------------------------------------------------------------------------ // Contract should not accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } /** * @notice Transfers vested tokens to Advisor. * @param _beneficiary ERC20 token which is being vested * @param _releaseAmount ERC20 token which is being vested */ function releaseToAdvisor(address _beneficiary, uint256 _releaseAmount) public onlyOwner{ require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); require(now >= releaseTimeToUnlockAdvisorTokens, "Release Advisor tokens on or after GMT: Wednesday, 21 August 2019 00:00:00"); uint256 releaseAmount = _releaseAmount.mul(E18); require(totalTokensIssuedToAdvisor.add(releaseAmount) <= ADVISORS_SUPPLY_LIMIT); balances[_beneficiary] = balances[_beneficiary].add(releaseAmount); totalTokensIssuedToAdvisor = totalTokensIssuedToAdvisor.add(releaseAmount); emit Released(_releaseAmount); } /** * @notice Transfers vested tokens to Early Investors. * @param _beneficiary ERC20 token which is being vested * @param _releaseAmount ERC20 token which is being vested */ function releaseToEarlyInvestors(address _beneficiary, uint256 _releaseAmount) public onlyOwner{ require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); require(now >= releaseTimeToUnlockEarlyInvestorTokens, "Release Early Investors tokens on or after GMT: Wednesday, 21 August 2019 00:00:00"); uint256 releaseAmount = _releaseAmount.mul(E18); require(totalTokensIssuedToEarlyInvestors.add(releaseAmount) <= EARLY_INVESTORS_SUPPLY_LIMIT); balances[_beneficiary] = balances[_beneficiary].add(releaseAmount); totalTokensIssuedToEarlyInvestors = totalTokensIssuedToEarlyInvestors.add(releaseAmount); emit Released(_releaseAmount); } /** * @notice Transfers vested tokens to Management Team. * @param _beneficiary ERC20 token which is being vested * @param _releaseAmount ERC20 token which is being vested */ function releaseToMgmtTeam(address _beneficiary, uint256 _releaseAmount) public onlyOwner{ require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); require(now >= releaseTimeToUnlockManagementTokens, "Release Mgmt Team tokens on or after GMT: Friday, 21 February 2020 00:00:00"); uint256 releaseAmount = _releaseAmount.mul(E18); require(totalTokensIssuedToMgmtTeam.add(releaseAmount) <= MANAGEMENT_TEAM_SUPPLY_LIMIT); balances[_beneficiary] = balances[_beneficiary].add(releaseAmount); totalTokensIssuedToMgmtTeam = totalTokensIssuedToMgmtTeam.add(releaseAmount); emit Released(_releaseAmount); } /** * @notice Start ICO. * @param start bool value */ function startICO(bool start) public onlyOwner{ isICORunning = start; } /** * @notice Set the ICO smart contract address. * @param _icoContract contract address of the ICO smart contract */ function setIcoContract(address _icoContract) public onlyOwner { // Allow to set the ICO contract only once require(icoContract == address(0)); require(_icoContract != address(0)); icoContract = _icoContract; } /** * @notice Reward Airdrop Participant. * @param _beneficiary wallet address of the Airdrop Participant * @param _amount number of tokens to be rewarded */ function rewardAirdrop(address _beneficiary, uint256 _amount) public onlyOwner { require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); uint256 amount = _amount.mul(E18); require (totalSupply_.add(amount) < TOTAL_SUPPLY_LIMIT); require(amount <= TOKEN_SUPPLY_AIRDROP_LIMIT); require(airDropTokenIssuedTotal < TOKEN_SUPPLY_AIRDROP_LIMIT); uint256 remainingTokens = TOKEN_SUPPLY_AIRDROP_LIMIT.sub(airDropTokenIssuedTotal); if (amount > remainingTokens) { amount = remainingTokens; } balances[_beneficiary] = balances[_beneficiary].add(amount); airDropTokenIssuedTotal = airDropTokenIssuedTotal.add(amount); balances[msg.sender] = balances[msg.sender].sub(amount); emit Transfer(address(AIRDROP_EVENT), _beneficiary, amount); } /** * @notice Reward Bounty Participant. * @param _beneficiary wallet address of the Bounty Participant * @param _amount number of tokens to be rewarded */ function rewardBounty(address _beneficiary, uint256 _amount) public onlyOwner { require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); uint256 amount = _amount.mul(E18); require (totalSupply_.add(amount) < TOTAL_SUPPLY_LIMIT); require(amount <= TOKEN_SUPPLY_BOUNTY_LIMIT); uint256 remainingTokens = TOKEN_SUPPLY_BOUNTY_LIMIT.sub(bountyTokenIssuedTotal); if (amount > remainingTokens) { amount = remainingTokens; } balances[_beneficiary] = balances[_beneficiary].add(amount); bountyTokenIssuedTotal = bountyTokenIssuedTotal.add(amount); balances[msg.sender] = balances[msg.sender].sub(amount); emit Transfer(address(BOUNTY_EVENT), _beneficiary, amount); } /** * @notice Pre ICO handler * @param _beneficiary wallet address of the Pre ICO Buyer * @param _amount number of tokens purchased */ function preICO(address _beneficiary, uint256 _amount) public onlyOwner { require(isWhitelisted(_beneficiary), "Buyer is not whitelisted"); uint256 amount = _amount.mul(E18); require (totalSupply_.add(amount) <= TOTAL_SUPPLY_LIMIT); uint256 remainingTokens = TOTAL_SUPPLY_LIMIT.sub(totalSupply_); require (amount <= remainingTokens); preICOTokenIssuedTotal = preICOTokenIssuedTotal.add(amount); super.mint(_beneficiary, amount); emit Transfer(address(PREICO_EVENT), _beneficiary, amount); } function preICOMany(address[] addrList, uint256[] amountList) public onlyOwner { require(addrList.length == amountList.length); for (uint256 i = 0; i < addrList.length; i++) { preICO(addrList[i], amountList[i]); } } /** * @notice ICO handler * @param buyer wallet address of the ICO Buyer * @param tokens number of tokens purchased */ function onICO(address buyer, uint256 tokens) public onlyOwner returns (bool success) { require(isICORunning); require(isWhitelisted(buyer), "Buyer is not whitelisted"); require (icoContract != address(0)); require (msg.sender == icoContract); require (tokens > 0); require (buyer != address(0)); require (totalSupply_.add(tokens) <= TOTAL_SUPPLY_LIMIT); super.mint(buyer, tokens); emit Transfer(address(ICO_EVENT), buyer, tokens); return true; } }
* @notice Transfers vested tokens to Early Investors. @param _beneficiary ERC20 token which is being vested @param _releaseAmount ERC20 token which is being vested/
function releaseToEarlyInvestors(address _beneficiary, uint256 _releaseAmount) public onlyOwner{ require(isWhitelisted(_beneficiary), "Beneficiary is not whitelisted"); require(now >= releaseTimeToUnlockEarlyInvestorTokens, "Release Early Investors tokens on or after GMT: Wednesday, 21 August 2019 00:00:00"); uint256 releaseAmount = _releaseAmount.mul(E18); require(totalTokensIssuedToEarlyInvestors.add(releaseAmount) <= EARLY_INVESTORS_SUPPLY_LIMIT); balances[_beneficiary] = balances[_beneficiary].add(releaseAmount); totalTokensIssuedToEarlyInvestors = totalTokensIssuedToEarlyInvestors.add(releaseAmount); emit Released(_releaseAmount); }
10,207,854
[ 1, 1429, 18881, 331, 3149, 2430, 358, 512, 20279, 5454, 395, 1383, 18, 225, 389, 70, 4009, 74, 14463, 814, 4232, 39, 3462, 1147, 1492, 353, 3832, 331, 3149, 225, 389, 9340, 6275, 4232, 39, 3462, 1147, 1492, 353, 3832, 331, 3149, 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, 3992, 774, 41, 20279, 3605, 395, 1383, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 9340, 6275, 13, 1071, 1338, 5541, 95, 203, 3639, 2583, 12, 291, 18927, 329, 24899, 70, 4009, 74, 14463, 814, 3631, 315, 38, 4009, 74, 14463, 814, 353, 486, 26944, 8863, 203, 3639, 2583, 12, 3338, 1545, 3992, 950, 774, 7087, 41, 20279, 3605, 395, 280, 5157, 16, 315, 7391, 512, 20279, 5454, 395, 1383, 2430, 603, 578, 1839, 21706, 30, 678, 329, 23712, 2881, 16, 9035, 432, 637, 641, 30562, 9631, 30, 713, 30, 713, 8863, 203, 540, 203, 3639, 2254, 5034, 3992, 6275, 273, 389, 9340, 6275, 18, 16411, 12, 41, 2643, 1769, 203, 3639, 2583, 12, 4963, 5157, 7568, 5957, 774, 41, 20279, 3605, 395, 1383, 18, 1289, 12, 9340, 6275, 13, 1648, 512, 985, 7076, 67, 706, 3412, 882, 14006, 67, 13272, 23893, 67, 8283, 1769, 203, 203, 3639, 324, 26488, 63, 67, 70, 4009, 74, 14463, 814, 65, 273, 324, 26488, 63, 67, 70, 4009, 74, 14463, 814, 8009, 1289, 12, 9340, 6275, 1769, 203, 203, 3639, 2078, 5157, 7568, 5957, 774, 41, 20279, 3605, 395, 1383, 273, 2078, 5157, 7568, 5957, 774, 41, 20279, 3605, 395, 1383, 18, 1289, 12, 9340, 6275, 1769, 203, 203, 3639, 3626, 10819, 72, 24899, 9340, 6275, 1769, 203, 225, 289, 203, 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 ]
./full_match/4/0xa3a58fAf3DcAe18a5F20792b1165AA609571C30d/sources/contract-867d3f40d0.sol
The following functions are overrides required by Solidity.
contract MyGovernor is Governor, GovernorSettings, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { constructor(IVotes _token, TimelockController _timelock) Governor("MyGovernor") GovernorSettings(1 /* 1 block */, 45818 /* 1 week */, 0) GovernorVotes(_token) GovernorVotesQuorumFraction(4) GovernorTimelockControl(_timelock) function votingDelay() public view override(IGovernor, GovernorSettings) returns (uint256) pragma solidity ^0.8.4; {} { return super.votingDelay(); } function votingPeriod() public view override(IGovernor, GovernorSettings) returns (uint256) { return super.votingPeriod(); } function quorum(uint256 blockNumber) public view override(IGovernor, GovernorVotesQuorumFraction) returns (uint256) { return super.quorum(blockNumber); } function getVotes(address account, uint256 blockNumber) public view override(IGovernor, GovernorVotes) returns (uint256) { return super.getVotes(account, blockNumber); } function state(uint256 proposalId) public view override(Governor, GovernorTimelockControl) returns (ProposalState) { return super.state(proposalId); } function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) public override(Governor, IGovernor) returns (uint256) { return super.propose(targets, values, calldatas, description); } function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { return super.proposalThreshold(); } function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) internal override(Governor, GovernorTimelockControl) { super._execute(proposalId, targets, values, calldatas, descriptionHash); } function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) internal override(Governor, GovernorTimelockControl) returns (uint256) { return super._cancel(targets, values, calldatas, descriptionHash); } function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) { return super._executor(); } function supportsInterface(bytes4 interfaceId) public view override(Governor, GovernorTimelockControl) returns (bool) { return super.supportsInterface(interfaceId); } }
12,444,234
[ 1, 1986, 3751, 4186, 854, 9515, 1931, 635, 348, 7953, 560, 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, 16351, 8005, 43, 1643, 29561, 353, 611, 1643, 29561, 16, 611, 1643, 29561, 2628, 16, 611, 1643, 29561, 1380, 310, 5784, 16, 611, 1643, 29561, 29637, 16, 611, 1643, 29561, 29637, 31488, 13724, 16, 611, 1643, 29561, 10178, 292, 975, 3367, 288, 203, 565, 3885, 12, 8188, 6366, 389, 2316, 16, 12652, 292, 975, 2933, 389, 8584, 292, 975, 13, 203, 3639, 611, 1643, 29561, 2932, 12062, 43, 1643, 29561, 7923, 203, 3639, 611, 1643, 29561, 2628, 12, 21, 1748, 404, 1203, 1195, 16, 1059, 8204, 2643, 1748, 404, 4860, 1195, 16, 374, 13, 203, 3639, 611, 1643, 29561, 29637, 24899, 2316, 13, 203, 3639, 611, 1643, 29561, 29637, 31488, 13724, 12, 24, 13, 203, 3639, 611, 1643, 29561, 10178, 292, 975, 3367, 24899, 8584, 292, 975, 13, 203, 203, 203, 565, 445, 331, 17128, 6763, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 12, 3047, 1643, 29561, 16, 611, 1643, 29561, 2628, 13, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 2618, 203, 565, 288, 203, 3639, 327, 2240, 18, 90, 17128, 6763, 5621, 203, 565, 289, 203, 203, 565, 445, 331, 17128, 5027, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 12, 3047, 1643, 29561, 16, 611, 1643, 29561, 2628, 13, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 2240, 18, 90, 17128, 5027, 5621, 203, 565, 289, 203, 203, 565, 445, 31854, 12, 11890, 5034, 1203, 1854, 13, 203, 2 ]
./partial_match/11155111/0x9B36F148D92494F144d8F70F60cCadC4b726194e/sources/nft/chainTransferAble/Tripster721ACreateFeeTransferChainSender.sol
uint256 _indexOfIpfsCollection = _indexOfCollectionId(collectionId);
function pause_mint(uint256 collectionIndex) public onlyOwner { IpfsCollections[collectionIndex].public_released = false; IpfsCollections[collectionIndex].whitelist_released = false; }
3,534,162
[ 1, 11890, 5034, 389, 31806, 5273, 2556, 2532, 273, 389, 31806, 2532, 548, 12, 5548, 548, 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 ]
[ 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, 565, 445, 11722, 67, 81, 474, 12, 11890, 5034, 1849, 1016, 13, 1071, 1338, 5541, 288, 203, 3639, 14709, 2556, 15150, 63, 5548, 1016, 8009, 482, 67, 9340, 72, 273, 629, 31, 203, 3639, 14709, 2556, 15150, 63, 5548, 1016, 8009, 20409, 67, 9340, 72, 273, 629, 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 ]
pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./Gravity.sol"; pragma experimental ABIEncoderV2; contract CronosGravity is Gravity, AccessControl, Pausable, Ownable { using SafeERC20 for IERC20; bytes32 public constant RELAYER = keccak256("RELAYER"); bytes32 public constant RELAYER_ADMIN = keccak256("RELAYER_ADMIN"); // modifier onlyRole(bytes32 role) { // require(hasRole(role, msg.sender), "CronosGravity::Permission Denied"); // _; // } bool public anyoneCanRelay; event AnyoneCanRelay(bool anyoneCanRelay); modifier checkWhiteList() { if (!anyoneCanRelay) { _checkRole(RELAYER, msg.sender); } _; } constructor ( // A unique identifier for this gravity instance to use in signatures bytes32 _gravityId, // How much voting power is needed to approve operations uint256 _powerThreshold, // The validator set address[] memory _validators, uint256[] memory _powers, address relayerAdmin ) Gravity( _gravityId, _powerThreshold, _validators, _powers ) { _setupRole(RELAYER_ADMIN, relayerAdmin); _setRoleAdmin(RELAYER, RELAYER_ADMIN); _setRoleAdmin(RELAYER_ADMIN, RELAYER_ADMIN); } // Admin functionalities: Those functions are intended to be removed in long term by setting the owner to zero address // however since the gravity is still in an experimental stage, safe guards are needed /** * Only owner * pause will deactivate contract functionalities */ function pause() public onlyOwner { _pause(); } /** * Only owner * unpause will re activate contract functionalities */ function unpause() public onlyOwner { _unpause(); } /** * Only owner * migrateToken allows to migrate locked fund to a new gravity contract * in case we need to upgrade it */ function migrateToken( address _tokenContract, address _destination, uint256 _amount ) public onlyOwner { IERC20(_tokenContract).safeTransfer(_destination, _amount); } // Pausable functionalities: // Those functions override the basic functionalities of the gravity contract function updateValset( // The new version of the validator set ValsetArgs calldata _newValset, // The current validators that approve the change ValsetArgs calldata _currentValset, // These are arrays of the parts of the current validator's signatures ValSignature[] calldata _sigs ) public override whenNotPaused checkWhiteList { super.updateValset(_newValset, _currentValset, _sigs); } function submitBatch( // The validators that approve the batch ValsetArgs calldata _currentValset, // These are arrays of the parts of the validators signatures ValSignature[] calldata _sigs, // The batch of transactions uint256[] calldata _amounts, address[] calldata _destinations, uint256[] calldata _fees, uint256 _batchNonce, address _tokenContract, // a block height beyond which this batch is not valid // used to provide a fee-free timeout uint256 _batchTimeout ) public override whenNotPaused checkWhiteList { super.submitBatch( _currentValset, _sigs, _amounts, _destinations, _fees, _batchNonce, _tokenContract, _batchTimeout ); } function submitLogicCall( // The validators that approve the call ValsetArgs calldata _currentValset, // These are arrays of the parts of the validators signatures ValSignature[] calldata _sigs, LogicCallArgs memory _args ) public override whenNotPaused checkWhiteList { super.submitLogicCall( _currentValset, _sigs, _args ); } function sendToCronos( address _tokenContract, address _destination, uint256 _amount ) public override whenNotPaused { super.sendToCronos( _tokenContract, _destination, _amount ); } function sendToCosmos( address _tokenContract, bytes32 _destination, uint256 _amount ) public override whenNotPaused { super.sendToCosmos( _tokenContract, _destination, _amount ); } function setAnyoneCanRelay ( bool _anyoneCanRelay ) public onlyRole(RELAYER_ADMIN) { anyoneCanRelay = _anyoneCanRelay; emit AnyoneCanRelay(anyoneCanRelay); } function transferRelayerAdmin ( address _newAdmin ) public onlyRole(RELAYER_ADMIN) { grantRole(RELAYER_ADMIN, _newAdmin); revokeRole(RELAYER_ADMIN, msg.sender); } }
modifier onlyRole(bytes32 role) { require(hasRole(role, msg.sender), "CronosGravity::Permission Denied"); _; }
contract CronosGravity is Gravity, AccessControl, Pausable, Ownable { using SafeERC20 for IERC20; bytes32 public constant RELAYER = keccak256("RELAYER"); bytes32 public constant RELAYER_ADMIN = keccak256("RELAYER_ADMIN"); bool public anyoneCanRelay; event AnyoneCanRelay(bool anyoneCanRelay); modifier checkWhiteList() { if (!anyoneCanRelay) { _checkRole(RELAYER, msg.sender); } _; } constructor ( uint256[] memory _powers, address relayerAdmin ) Gravity( _gravityId, _powerThreshold, _validators, _powers modifier checkWhiteList() { if (!anyoneCanRelay) { _checkRole(RELAYER, msg.sender); } _; } constructor ( uint256[] memory _powers, address relayerAdmin ) Gravity( _gravityId, _powerThreshold, _validators, _powers bytes32 _gravityId, uint256 _powerThreshold, address[] memory _validators, ) { _setupRole(RELAYER_ADMIN, relayerAdmin); _setRoleAdmin(RELAYER, RELAYER_ADMIN); _setRoleAdmin(RELAYER_ADMIN, RELAYER_ADMIN); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function migrateToken( address _tokenContract, address _destination, uint256 _amount ) public onlyOwner { IERC20(_tokenContract).safeTransfer(_destination, _amount); } function updateValset( ValsetArgs calldata _newValset, ValsetArgs calldata _currentValset, ValSignature[] calldata _sigs ) public override whenNotPaused checkWhiteList { super.updateValset(_newValset, _currentValset, _sigs); } function submitBatch( ValsetArgs calldata _currentValset, ValSignature[] calldata _sigs, uint256[] calldata _amounts, address[] calldata _destinations, uint256[] calldata _fees, uint256 _batchNonce, address _tokenContract, uint256 _batchTimeout ) public override whenNotPaused checkWhiteList { super.submitBatch( _currentValset, _sigs, _amounts, _destinations, _fees, _batchNonce, _tokenContract, _batchTimeout ); } function submitLogicCall( ValsetArgs calldata _currentValset, ValSignature[] calldata _sigs, LogicCallArgs memory _args ) public override whenNotPaused checkWhiteList { super.submitLogicCall( _currentValset, _sigs, _args ); } function sendToCronos( address _tokenContract, address _destination, uint256 _amount ) public override whenNotPaused { super.sendToCronos( _tokenContract, _destination, _amount ); } function sendToCosmos( address _tokenContract, bytes32 _destination, uint256 _amount ) public override whenNotPaused { super.sendToCosmos( _tokenContract, _destination, _amount ); } function setAnyoneCanRelay ( bool _anyoneCanRelay ) public onlyRole(RELAYER_ADMIN) { anyoneCanRelay = _anyoneCanRelay; emit AnyoneCanRelay(anyoneCanRelay); } function transferRelayerAdmin ( address _newAdmin ) public onlyRole(RELAYER_ADMIN) { grantRole(RELAYER_ADMIN, _newAdmin); revokeRole(RELAYER_ADMIN, msg.sender); } }
1,052,284
[ 1, 20597, 1338, 2996, 12, 3890, 1578, 2478, 13, 288, 3639, 2583, 12, 5332, 2996, 12, 4615, 16, 1234, 18, 15330, 3631, 315, 18586, 538, 14571, 16438, 2866, 5041, 22453, 2092, 8863, 3639, 389, 31, 565, 289, 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, 16351, 18972, 538, 14571, 16438, 353, 10812, 16438, 16, 24349, 16, 21800, 16665, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 15375, 5255, 654, 273, 417, 24410, 581, 5034, 2932, 862, 22166, 8863, 203, 565, 1731, 1578, 1071, 5381, 15375, 5255, 654, 67, 15468, 273, 417, 24410, 581, 5034, 2932, 862, 22166, 67, 15468, 8863, 203, 203, 203, 565, 1426, 1071, 1281, 476, 2568, 27186, 31, 203, 203, 565, 871, 5502, 476, 2568, 27186, 12, 6430, 1281, 476, 2568, 27186, 1769, 203, 203, 565, 9606, 866, 13407, 682, 1435, 288, 203, 3639, 309, 16051, 2273, 476, 2568, 27186, 13, 288, 203, 7734, 389, 1893, 2996, 12, 862, 22166, 16, 1234, 18, 15330, 1769, 203, 5411, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 261, 203, 3639, 2254, 5034, 8526, 3778, 389, 23509, 414, 16, 203, 3639, 1758, 1279, 1773, 4446, 203, 565, 262, 10812, 16438, 12, 203, 3639, 389, 2752, 16438, 548, 16, 203, 3639, 389, 12238, 7614, 16, 203, 3639, 389, 23993, 16, 203, 3639, 389, 23509, 414, 203, 565, 9606, 866, 13407, 682, 1435, 288, 203, 3639, 309, 16051, 2273, 476, 2568, 27186, 13, 288, 203, 7734, 389, 1893, 2996, 12, 862, 22166, 16, 1234, 18, 15330, 1769, 203, 5411, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 261, 203, 3639, 2254, 5034, 8526, 3778, 389, 23509, 414, 16, 203, 3639, 1758, 1279, 1773, 4446, 203, 565, 262, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-14 */ /* Fee Percentages 1. 6% Team wallet 2. 5% Raid wallet 3. 5% Reward Reflection (auto) total: 16% tg: https://t.me/shartans Supply 10,000,000,000 SPDX-License-Identifier: MIT */ pragma solidity ^0.8.4; /** * @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; } } /** * @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); } } // 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; } } } /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } /** * @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); } } } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /** * @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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: 3000}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe().add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account].sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account].add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } ///////// Uniswap Interfaces /////////// interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); 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); } interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHARTAN is ERC20, Ownable { using SafeMath for uint256; using Address for address; uint256 private launchedAt; uint256 private _initialTotalSupply = 10**10 * 10**18; uint8 private _decimals = 18; uint256 private _maxTxAmount = 5 * 10**8 * 10**18; uint256 private _minSwapTokenAmount = 10**7 * 10 ** 18; // Fees 16% uint256 private _devFee = 60; // 6% Dev Fee uint256 private _raidFee = 50; // 5% Raid Fee uint256 private _rewardFee = 50; // 5% Reward Fee // uint256 private _initialSellTotalFee = 240; // 24% Total Fee: Reward + Dev + Raid //Addresses address private _devWalletAddress = 0xBE493264335B34B0219136e3e095aE419fAD495b; address private _raidWalletAddress = 0xcB62829a45EF72392d8a44CBD3582872f556CA5f; // Mappings mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) private blacklist; // blacklist bool private buyCooldownEnabled = true; mapping(address => uint256) private boughtTimes; // could be subject to a maximum transfer amount mapping (address => bool) private automatedMarketMakerPairs; SHARTANDividendTracker public dividendTracker; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; // use by default 300,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 300000; bool inSwapping; bool private swapAndLiquifyEnabled = true; bool private tradeEnabled = false; bool private sellCooldownEnabled = true; event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); modifier lockTheSwap { inSwapping = true; _; inSwapping = false; } constructor () ERC20("SHARTAN INU", "SHARTAN") { launchedAt = block.timestamp; dividendTracker = new SHARTANDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap router // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _setAutomatedMarketMakerPair(uniswapV2Pair, true); //exclude owner, this contract, hero pool from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_devWalletAddress] = true; _isExcludedFromFee[_raidWalletAddress] = true; dividendTracker.excludeFromDividends(address(this)); _mint(owner(), _initialTotalSupply); } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "SHARTAN: The dividend tracker already has that address"); SHARTANDividendTracker newDividendTracker = SHARTANDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "SHARTAN: The new dividend tracker must be owned by the SHARTAN token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setDevWallet(address account) public onlyOwner { _devWalletAddress = account; } function setRaidWallet(address account) public onlyOwner { _raidWalletAddress = account; } function setDevFeePercent(uint256 _percent) public onlyOwner { _devFee = _percent; } function setRaidFeePercent(uint256 _percent) public onlyOwner { _raidFee = _percent; } function setRewardFeePercent(uint256 _percent) public onlyOwner { _rewardFee = _percent; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _initialTotalSupply.mul(maxTxPercent).div( 10**4 ); } function setMinSwapTokenAmount(uint256 amount) external onlyOwner { _minSwapTokenAmount = amount; } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "SHARTAN: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "SHARTAN: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setTradeEnabled(bool _enabled) external onlyOwner { tradeEnabled = _enabled; } function setSellCooldownEnabled(bool _enabled) external onlyOwner { sellCooldownEnabled = _enabled; } function setBuyCooldownEnabled(bool _enabled) external onlyOwner { buyCooldownEnabled = _enabled; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != uniswapV2Pair, "SHARTAN: The UniSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "SHARTAN: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } } function excludeFromBlacklist(address account) external onlyOwner() { require(blacklist[account], "Account is already excluded in blacklist"); blacklist[account] = false; } function includeInBlacklist(address account) external onlyOwner() { require(!blacklist[account], "Account is already included in blacklist"); blacklist[account] = true; } // to recieve ETH from uniswapV2Router when swaping receive() external payable {} function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function swapTokensForEth(uint256 tokenAmount) private { // generate the pancakeswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapAndSendFees(uint256 tokens) private lockTheSwap { swapTokensForEth(tokens); uint256 tokenBalance = address(this).balance; uint256 totalFees = _devFee.add(_raidFee).add(_rewardFee); uint256 devFee = tokenBalance.mul(_devFee).div(totalFees); (bool success1,) = address(_devWalletAddress).call{value: devFee}(""); require(success1, 'No success1'); uint256 raidFee = tokenBalance.mul(_raidFee).div(totalFees); (bool success2,) = address(_raidWalletAddress).call{value: raidFee}(""); require(success2, 'No success2'); uint256 dividends = tokenBalance.sub(devFee).sub(raidFee); (bool success,) = address(dividendTracker).call{value: dividends}(""); if(success) { emit SendDividends(tokens, dividends); } } 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(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); require(!blacklist[from] && !blacklist[to], "Blacklist transaction"); } if (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]) { require(tradeEnabled, "Trade is not enabled yet"); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is pancakeswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _minSwapTokenAmount; if ( overMinTokenBalance && !inSwapping && !automatedMarketMakerPairs[from] && swapAndLiquifyEnabled ) { if (contractTokenBalance > _maxTxAmount) { contractTokenBalance = _maxTxAmount; } swapAndSendFees(contractTokenBalance); } // buy cooldown if (buyCooldownEnabled && automatedMarketMakerPairs[from]) { require((boughtTimes[from] + 15 minutes) < block.timestamp, "Wait 15 minutes to buy another"); boughtTimes[from] = block.timestamp; } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } if(takeFee) { uint256 totalFees = _devFee.add(_raidFee).add(_rewardFee); // Sell Fee(24%) for first 2 days if (sellCooldownEnabled && automatedMarketMakerPairs[to] && (launchedAt + 2 days) > block.timestamp) { totalFees = totalFees.mul(15).div(10); // 1.5 times 24% } uint256 fees = amount.div(1000).mul(totalFees); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} if(!inSwapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch {} } } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } } contract SHARTANDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public immutable minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("SHARTAN_Dividend_Tracker", "SHARTAN_Dividend_Tracker") { claimWait = 3600; minimumTokenBalanceForDividends = 10**2 * (10**18); //must hold 40,000+ tokens } function _transfer(address, address, uint256) internal pure override { require(false, "SHARTAN_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "SHARTAN_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main SHARTAN contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "SHARTAN_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "SHARTAN_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if(index >= 0) { if(uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if(index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if(lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if(excludedFromDividends[account]) { return; } if(newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if(numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while(gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if(_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if(canAutoClaim(lastClaimTimes[account])) { if(processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if(gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if(amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
Uniswap Interfaces //
interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); }
7,976,007
[ 1, 984, 291, 91, 438, 27152, 368, 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, 5831, 467, 984, 291, 91, 438, 58, 22, 1733, 288, 203, 565, 871, 8599, 6119, 12, 2867, 8808, 1147, 20, 16, 1758, 8808, 1147, 21, 16, 1758, 3082, 16, 2254, 1769, 203, 565, 445, 1689, 1826, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 203, 565, 445, 752, 4154, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1135, 261, 2867, 3082, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "../Plus.sol"; import "./MockToken.sol"; /** * @dev Mock plus implementation. */ contract MockPlus is Plus { uint256 public underlyingAmount; function initialize(string memory _name, string memory _symbol) public { __PlusToken__init(_name, _symbol); } /** * @dev Returns the total value of the plus token in terms of the peg value. * All underlying token amounts have been scaled to 18 decimals. * For single plus, it's equal to its total supply. * For composite plus, it's equal to the total amount of single plus tokens in its basket. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { return underlyingAmount * WAD; } function increment(uint256 amount) public { underlyingAmount = underlyingAmount + amount; } function mintShares(address user, uint256 amount) public { totalShares += amount; userShare[user] += amount; underlyingAmount += amount * index / WAD; } /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view override returns (bool) { underlyingAmount; return _token != address(0x0); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } }
* @dev Checks whether a token can be salvaged via salvageToken(). @param _token Token to check salvageability./
function _salvageable(address _token) internal view override returns (bool) { underlyingAmount; return _token != address(0x0); }
7,292,861
[ 1, 4081, 2856, 279, 1147, 848, 506, 12814, 90, 11349, 3970, 12814, 90, 410, 1345, 7675, 225, 389, 2316, 3155, 358, 866, 12814, 90, 410, 2967, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 21982, 90, 410, 429, 12, 2867, 389, 2316, 13, 2713, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 6808, 6275, 31, 203, 3639, 327, 389, 2316, 480, 1758, 12, 20, 92, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-30 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /////////////////////////////////////// // ____ __ ___ __ __ // // /_ / ___ __\ \/ (_)__ / /__/ / // // / /_/ -_) _ \ / / -_) / _ / // // /___/\__/_//_/_/_/\__/_/\_,_/ // // by 0xInuarashi.eth // /////////////////////////////////////// abstract contract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender, "Not Owner!"); _; } function transferOwnership(address new_) external onlyOwner { owner = new_; } } interface iZen { function mintAsController(address to_, uint256 amount_) external; } interface iZenApe { function balanceOf(address address_) external view returns (uint256); } contract ZenYield is Ownable { // Interfaces iZen public Zen = iZen(0x0fAD2A1F9aB421C1740c0456ec62c155518824aF); function setZen(address address_) external onlyOwner { Zen = iZen(address_); } iZenApe public ZenApe = iZenApe(0x838804a3dd7c717396a68F94E736eAf76b911632); function setZenApe(address address_) external onlyOwner { ZenApe = iZenApe(address_); } // Times uint40 public yieldStartTime = 1651327200; // Apr 30 2022 14:00:00 GMT+0000 uint40 public yieldEndTime = 1682863200; // Apr 30 2023 14:00:00 GMT+0000 function setYieldEndTime(uint40 yieldEndTime_) external onlyOwner { yieldEndTime = yieldEndTime_; } // Yield Info uint256 public globalModulus = 10e14; // Round up 14 Decimals uint256 public yieldRatePerToken = 5 ether / globalModulus; // 5 Zen per Day struct Yield { uint40 lastUpdateTime; uint216 pendingRewards; } mapping(address => Yield) public addressToYield; // Events event Claim(address to_, uint256 amount_, uint256 time_); event CreditsDeducted(address from_, uint256 amount_); event CreditsAdded(address to_, uint256 amount_); // Internal Calculators function _getSmallerValueUint40(uint40 a, uint40 b) internal pure returns (uint40) { return a < b ? a : b; } function _getTimestamp() internal view returns (uint40) { return _getSmallerValueUint40( uint40(block.timestamp), yieldEndTime ); } function _getYieldRate(address address_) internal view returns (uint40) { return uint40(ZenApe.balanceOf(address_) * yieldRatePerToken); } // Internal Accountants function _getPendingRewards(address address_) internal view returns (uint216) { uint256 _totalYieldRate = uint256(_getYieldRate(address_)); if (_totalYieldRate == 0) return 0; uint256 _time = uint256(_getTimestamp()); uint256 _lastUpdate = uint256(addressToYield[address_].lastUpdateTime); if (_lastUpdate > yieldStartTime) { return uint216( (_totalYieldRate * (_time - _lastUpdate) / 1 days) ); } // Has ZenApe before Zen Token else if (_lastUpdate == 0 && _totalYieldRate > 0) { return uint216( (_totalYieldRate * (_time - yieldStartTime) / 1 days) ); } else { return 0; } } function _updateReward(address address_) internal { uint40 _lastUpdate = addressToYield[address_].lastUpdateTime; if (_lastUpdate > 0) { addressToYield[address_].pendingRewards += _getPendingRewards(address_); } // Has ZenApe before Zen Token else if (_lastUpdate == 0 && ZenApe.balanceOf(address_) != 0) { addressToYield[address_].pendingRewards += _getPendingRewards(address_); } if (_lastUpdate != yieldEndTime) { addressToYield[address_].lastUpdateTime = _getTimestamp(); } } function _claimReward(address address_) internal { // This does not update before claim. So, in internal flows, update first. uint216 _pendingRewards = addressToYield[address_].pendingRewards; if (_pendingRewards > 0) { uint256 _expandedReward = uint256(_pendingRewards * globalModulus); addressToYield[address_].pendingRewards = 0; Zen.mintAsController(address_, _expandedReward); } } // ZenApe Functions function updateReward(address from_, address to_, uint256 tokenId_) public { require(msg.sender == address(ZenApe), "You are not ZenApe!"); _updateReward(from_); _updateReward(to_); } // Public Functions function updateRewardFor(address address_) public { _updateReward(address_); } function claimReward(address address_) public { _updateReward(address_); _claimReward(address_); } // View Functions function getYieldRateOfAddress(address address_) public view returns (uint256) { return uint256( uint256(_getYieldRate(address_)) * globalModulus); } function getStorageClaimableTokens(address address_) public view returns (uint256) { return uint256( uint256( addressToYield[address_].pendingRewards) * globalModulus); } function getPendingClaimableTokens(address address_) public view returns (uint256) { return uint256( uint256(_getPendingRewards(address_)) * globalModulus ); } function getTotalClaimableTokens(address address_) public view returns (uint256) { return getStorageClaimableTokens(address_) + getPendingClaimableTokens(address_); } function raw_getStorageClaimableTokens(address address_) public view returns (uint256) { return uint256(addressToYield[address_].pendingRewards); } function raw_getPendingClaimableTokens(address address_) public view returns (uint256) { return uint256(_getPendingRewards(address_)); } function raw_getTotalClaimableTokens(address address_) public view returns (uint256) { return raw_getStorageClaimableTokens(address_) + raw_getPendingClaimableTokens(address_); } }
Apr 30 2022 14:00:00 GMT+0000
uint40 public yieldStartTime = 1651327200;
15,077,009
[ 1, 37, 683, 5196, 26599, 22, 5045, 30, 713, 30, 713, 21706, 15, 2787, 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, 2254, 7132, 1071, 2824, 13649, 273, 2872, 10593, 1578, 27, 6976, 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 ]
//Address: 0x93012a1c354b2964ef88a55b7b11ed178f921b3e //Contract name: AffiliateManager //Balance: 0 Ether //Verification Date: 2/13/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns(uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns(uint256); function transferFrom(address from, address to, uint256 value) public returns(bool); function approve(address spender, uint256 value) public returns(bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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; } } /** * @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; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * 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); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns(bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns(bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns(bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns(bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns(bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns(bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title MavinToken * @dev ERC20 mintable token * The token will be minted by the crowdsale contract only */ contract MavinToken is MintableToken, PausableToken { string public constant name = "Mavin Token"; string public constant symbol = "MVN"; uint8 public constant decimals = 18; address public creator; function MavinToken() public Ownable() MintableToken() PausableToken() { creator = msg.sender; paused = true; } function finalize() public onlyOwner { finishMinting(); //this can't be reactivated unpause(); } function ownershipToCreator() public { require(creator == msg.sender); owner = msg.sender; } } /** * @author OpenZeppelin * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } library Referral { /** * @dev referral tree */ event LogRef(address member, address referrer); struct Node { address referrer; bool valid; } /** * @dev tree is a collection of nodes */ struct Tree { mapping(address => Referral.Node) nodes; } function addMember( Tree storage self, address _member, address _referrer ) internal returns(bool success) { Node memory memberNode; memberNode.referrer = _referrer; memberNode.valid = true; self.nodes[_member] = memberNode; LogRef(_member, _referrer); return true; } } contract AffiliateTreeStore is Ownable { using SafeMath for uint256; using Referral for Referral.Tree; address public creator; Referral.Tree affiliateTree; function AffiliateTreeStore() public { creator = msg.sender; } function ownershipToCreator() public { require(creator == msg.sender); owner = msg.sender; } function getNode( address _node ) public view returns(address referrer) { Referral.Node memory n = affiliateTree.nodes[_node]; if (n.valid == true) { return _node; } return 0; } function getReferrer( address _node ) public view returns(address referrer) { Referral.Node memory n = affiliateTree.nodes[_node]; if (n.valid == true) { return n.referrer; } return 0; } function addMember( address _member, address _referrer ) public onlyOwner returns(bool success) { return affiliateTree.addMember(_member, _referrer); } // Fallback Function only ETH with no functionCall function() public { revert(); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping(address => uint256) public released; mapping(address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns(uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns(uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } contract AffiliateManager is Pausable { using SafeMath for uint256; AffiliateTreeStore public affiliateTree; // treeStorage // The token being sold MavinToken public token; // endTime uint256 public endTime; // hardcap uint256 public cap; // address where funds are collected address public vault; // how many token units a referral gets per eth uint256 public mvnpereth; // how many token units a buyer gets per eth uint256 public mvnperethBonus; // amount of raised money in wei uint256 public level1Bonus; uint256 public level2Bonus; // amount of raised money in wei uint256 public weiRaised; // min contribution amount uint256 public minAmountWei; // creator address creator; function AffiliateManager( address _token, address _treestore ) public { creator = msg.sender; token = MavinToken(_token); endTime = 1536969600; // Sat Sep 15 01:00:00 2018 GMT+1 vault = 0xD0b40D3bfd8DFa6ecC0b357555039C3ee1C11202; mvnpereth = 100; mvnperethBonus = 105; level1Bonus = 8; level2Bonus = 5; minAmountWei = 0.01 ether; cap = 32000 ether; affiliateTree = AffiliateTreeStore(_treestore); } /// Log buyTokens event LogBuyTokens(address owner, uint256 tokens, uint256 tokenprice); /// Log LogId event LogId(address owner, uint48 id); modifier onlyNonZeroAddress(address _a) { require(_a != address(0)); _; } modifier onlyDiffAdr(address _referrer, address _sender) { require(_referrer != _sender); _; } function initAffiliate() public onlyOwner returns(bool) { //create first 2 root nodes bool success1 = affiliateTree.addMember(vault, 0); //root bool success2 = affiliateTree.addMember(msg.sender, vault); //root+1 return success1 && success2; } // execute after all crowdsale tokens are minted function finalizeCrowdsale() public onlyOwner returns(bool) { pause(); uint256 totalSupply = token.totalSupply(); // 6 month cliff, 12 month total TokenVesting team = new TokenVesting(vault, now, 24 weeks, 1 years, false); uint256 teamTokens = totalSupply.div(60).mul(16); token.mint(team, teamTokens); uint256 reserveTokens = totalSupply.div(60).mul(18); token.mint(vault, reserveTokens); uint256 advisoryTokens = totalSupply.div(60).mul(6); token.mint(vault, advisoryTokens); token.transferOwnership(creator); } function validPurchase() internal constant returns(bool) { bool withinCap = weiRaised.add(msg.value) <= cap; bool withinTime = endTime > now; bool withinMinAmount = msg.value >= minAmountWei; return withinCap && withinTime && withinMinAmount; } function presaleMint( address _beneficiary, uint256 _amountmvn, uint256 _mvnpereth ) public onlyOwner returns(bool) { uint256 _weiAmount = _amountmvn.div(_mvnpereth); require(_beneficiary != address(0)); token.mint(_beneficiary, _amountmvn); // update state weiRaised = weiRaised.add(_weiAmount); LogBuyTokens(_beneficiary, _amountmvn, _mvnpereth); return true; } function joinManual( address _referrer, uint48 _id ) public payable whenNotPaused onlyDiffAdr(_referrer, msg.sender) // prevent selfreferal onlyDiffAdr(_referrer, this) // prevent reentrancy returns(bool) { LogId(msg.sender, _id); return join(_referrer); } function join( address _referrer ) public payable whenNotPaused onlyDiffAdr(_referrer, msg.sender) // prevent selfreferal onlyDiffAdr(_referrer, this) // prevent reentrancy returns(bool success) { uint256 weiAmount = msg.value; require(_referrer != vault); require(validPurchase()); //respect min amount / cap / date //get existing sender node address senderNode = affiliateTree.getNode(msg.sender); // if senderNode already exists use same referrer if (senderNode != address(0)) { _referrer = affiliateTree.getReferrer(msg.sender); } //get referrer address referrerNode = affiliateTree.getNode(_referrer); //referrer must exist require(referrerNode != address(0)); //get referrer of referrer address topNode = affiliateTree.getReferrer(_referrer); //referrer of referrer must exist require(topNode != address(0)); require(topNode != msg.sender); //selfreferal // Add sender to the tree if (senderNode == address(0)) { affiliateTree.addMember(msg.sender, _referrer); } buyTokens(msg.sender, weiAmount, _referrer, true); uint256 parentAmount = 0; uint256 rootAmount = 0; //p1 parentAmount = weiAmount.div(100).mul(level1Bonus); //% commision for p1 referrerNode.transfer(parentAmount); buyTokens(referrerNode, parentAmount,_referrer, false); //p2 rootAmount = weiAmount.div(100).mul(level2Bonus); //% commision for p2 topNode.transfer(rootAmount); buyTokens(topNode, rootAmount,_referrer, false); vault.transfer(weiAmount.sub(parentAmount).sub(rootAmount)); //rest goes to vault return success; } function buyTokens( address _beneficiary, uint256 _weiAmount, address _referrer, bool _hasBonus ) internal returns(bool success) { require(_beneficiary != address(0)); uint256 tokens = 0; uint256 rate = mvnpereth; if (_hasBonus == true && _referrer != creator) { rate = mvnperethBonus; } tokens = _weiAmount.mul(rate); // update state weiRaised = weiRaised.add(_weiAmount); success = token.mint(_beneficiary, tokens); LogBuyTokens(_beneficiary, tokens, rate); return success; } function updateBonus(uint256 _minAmountWei, uint256 _buyerrate, uint256 _rate, uint256 _level1, uint256 _level2) onlyOwner public returns(bool success) { minAmountWei = _minAmountWei; mvnpereth = _rate; mvnperethBonus = _buyerrate; level1Bonus = _level1; level2Bonus = _level2; return true; } function presaleAddTree(address _wallet, address _referrer) onlyOwner public returns (bool success) { address node = affiliateTree.getNode(_wallet); //node must not exist require(node == address(0)); return affiliateTree.addMember(_wallet, _referrer); } function balanceOf(address _owner) public constant returns(uint256 balance) { return token.balanceOf(_owner); } // Fallback Function only ETH with no functionCall function() public { revert(); } }
* @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]; }
12,767,882
[ 1, 3002, 326, 11013, 434, 326, 1269, 1758, 18, 225, 389, 8443, 1021, 1758, 358, 843, 326, 326, 11013, 434, 18, 327, 1922, 2254, 5034, 5123, 326, 3844, 16199, 635, 326, 2275, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 12, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 8443, 15533, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.13; /* Main functionality: 2% fee on entry and 2% fee on exit deducted from input/output amount and distributed to all current share holders proportional to their position in the pool Extended stake bonuses [optional]: 30 days = 50% 60 days = 125% 90 days = 238% -15% penalty when unstaking extended stake early (distributed to share holders similar to entry/exit fee) Feature #1 - The airdrop: Admin (or anyone else) can distribute 100% of their deposit among all active share holders Feature #2 - The drip: Earn "emissionRate" set by admin per second per 1 token deposited into the pool default emissionRate is 0.00000001 tokens per second per 1 token user has deposited */ contract Staking { constructor(address _stakingToken, uint256 _emissionRate) public { erc20 = TOKEN(address(_stakingToken)); // set the staking token admin = msg.sender; // set the admin emissionRate = _emissionRate; // set the default emission rate (admin can change this later) // set the extended staking options stakeOptions[0] = StakeOption(30 days, 50); // 50% after 30 days stakeOptions[1] = StakeOption(60 days, 125); // 125% after 60 days stakeOptions[2] = StakeOption(90 days, 238); // 238% after 90 days } using SafeMath for uint256; // Declare the staking token TOKEN erc20; // Admin is payable so they can withdraw any ETH that may be sent here accidentally address payable admin; // Total balance of all users in the pool // This has the entry fee already applied so should always be < erc20.balanceOf(address(this)) uint256 public totalBalance; // How many staking tokens to reward per second per 1 deposited token uint256 public emissionRate; // All providers aka. the users / stakers in the system mapping(address => Provider) public provider; // All stakes mapped to their owners mapping(address => Stake[]) public stakes; // Extended stake options mapping(uint8 => StakeOption) public stakeOptions; // For admin only functions modifier isAdmin() { require(admin == msg.sender, "Admin only function"); _; } // Events event Deposit(address _user, uint256 _amount, uint256 _timestamp); event Withdraw(address _user, uint256 _amount, uint256 _timestamp); event ExtendedStake(address _user, uint256 _amount, uint8 _stakeOption, uint256 _timestamp); event StakeEndWithBonus(address _user, uint256 _bonus, uint256 _timestamp); event StakeEndWithPenalty(address _user, uint256 _amount, uint256 _timestamp); event ClaimDrip(address _user, uint256 _amount, uint256 _timestamp); event Airdrop(address _sender, uint256 _amount, uint256 _timestamp); event EmissionRateChanged(uint256 _newEmissionRate); // Extended stake struct Stake { uint256 amount; // amount of tokens staked uint32 unlockDate; // unlocks at this timestamp uint8 stakeBonus; // the +% bonus this stake gives } // Stake option, we have 3 of them struct StakeOption { uint32 duration; uint8 bonusPercent; } // User data struct Provider { uint256 commitAmount; // user's extended stake aka. the locked amount uint256 balance; // user's available balance (to extended stake or to withdraw) uint256 dripBalance; // total drips collected before last deposit uint32 lastUpdateAt; // timestamp for last update when dripBalance was calculated } // Function to deposit tokens into the pool function depositIntoPool(uint256 _depositAmount) public { // Check and transfer tokens here require( erc20.transferFrom(msg.sender, address(this), _depositAmount) == true, "transferFrom did not succeed. Are we approved?" ); // Declare the user Provider storage user = provider[msg.sender]; if (user.balance > 0) { // User has previously staked so calculate the new dripBalance user.dripBalance = dripBalance(msg.sender); } // deduct the 2% entry fee uint256 balanceToAdd = SafeMath.sub(_depositAmount, SafeMath.div(_depositAmount, 50)); user.balance = SafeMath.add(user.balance, balanceToAdd); user.lastUpdateAt = uint32(now); totalBalance = SafeMath.add(totalBalance, balanceToAdd); emit Deposit(msg.sender, _depositAmount, now); } // Function to withdraw all available balance (including dripped rewards) from the pool // Does not include the extended stake (locked) balances, if any exist function withdrawFromPool(uint256 _amount) public { Provider storage user = provider[msg.sender]; uint256 availableBalance = SafeMath.sub(user.balance, user.commitAmount); require(_amount <= availableBalance, "Amount withdrawn exceeds available balance"); // Claim all dripped rewards first claimDrip(); // deduct the 2% exit fee uint256 amountToWithdraw = SafeMath.div(SafeMath.mul(_amount, 49), 50); uint256 contractBalance = erc20.balanceOf(address(this)); // tokens in the contract * withdraw amount with fee / total balance with fee(s) uint256 amountToSend = SafeMath.div(SafeMath.mul(contractBalance, amountToWithdraw), totalBalance); // Subtract the amount user.balance = SafeMath.sub(user.balance, _amount); totalBalance = SafeMath.sub(totalBalance, _amount); // Transfer erc20.transfer(msg.sender, amountToSend); emit Withdraw(msg.sender, _amount, now); } // Function to enter an extended stake for a fixed period of time function extendedStake(uint256 _amount, uint8 _stakeOption) public { // We only have 0, 1, 2 options require(_stakeOption <= 2, "Invalid staking option"); Provider storage user = provider[msg.sender]; uint256 availableBalance = SafeMath.sub(user.balance, user.commitAmount); require(_amount <= availableBalance, "Stake amount exceeds available balance"); // Set unlock date and bonus from chosen option uint32 unlockDate = uint32(now) + stakeOptions[_stakeOption].duration; uint8 stakeBonus = stakeOptions[_stakeOption].bonusPercent; // Add as commitAmount user.commitAmount = SafeMath.add(user.commitAmount, _amount); // Push the new stake stakes[msg.sender].push(Stake(_amount, unlockDate, stakeBonus)); emit ExtendedStake(msg.sender, _amount, _stakeOption, now); } // Function to exit an extended stake // Distributes reward if unlockDate has passed or deducts a -15% penalty if it's a premature exit function claimStake(uint256 _stakeId) public { // Make sure the _stakeId provided is within range uint256 playerStakeCount = stakes[msg.sender].length; require(_stakeId < playerStakeCount, "Stake does not exist"); // Declare a user's stake & require it to have an amount Stake memory stake = stakes[msg.sender][_stakeId]; require(stake.amount > 0, "Invalid stake amount"); // Maintains the stake array length if (playerStakeCount > 1) { stakes[msg.sender][_stakeId] = stakes[msg.sender][playerStakeCount - 1]; } delete stakes[msg.sender][playerStakeCount - 1]; stakes[msg.sender].length--; Provider storage user = provider[msg.sender]; if (stake.unlockDate <= now) { // Stake duration has passed here. Distribute the stakeBonus reward! uint256 balanceToAdd = SafeMath.div(SafeMath.mul(stake.amount, stake.stakeBonus), 100); totalBalance = SafeMath.add(totalBalance, balanceToAdd); user.commitAmount = SafeMath.sub(user.commitAmount, stake.amount); user.balance = SafeMath.add(user.balance, balanceToAdd); emit StakeEndWithBonus(msg.sender, balanceToAdd, now); } else { // Stake duration has not passed. Apply the 15% penalty uint256 weightToRemove = SafeMath.div(SafeMath.mul(3, stake.amount), 20); user.balance = SafeMath.sub(user.balance, weightToRemove); totalBalance = SafeMath.sub(totalBalance, weightToRemove); user.commitAmount = SafeMath.sub(user.commitAmount, stake.amount); emit StakeEndWithPenalty(msg.sender, weightToRemove, now); } } // Function to claim dripped rewards function claimDrip() public { Provider storage user = provider[msg.sender]; uint256 amountToSend = dripBalance(msg.sender); user.dripBalance = 0; user.lastUpdateAt = uint32(now); erc20.transfer(msg.sender, amountToSend); emit ClaimDrip(msg.sender, amountToSend, now); } // Airdrop to pool // Anyone can airdrop tokens into the pool. Since withdrawFromPool() uses contractBalance = erc20.balanceOf(address(this)) // in its calculations, everything extra sent to our contract will get distributed proportionally when user withdraws from pool function airdrop(uint256 _amount) external { require( erc20.transferFrom(msg.sender, address(this), _amount) == true, "transferFrom did not succeed. Are we approved?" ); emit Airdrop(msg.sender, _amount, now); } // Admin can edit the emissionRate function changeEmissionRate(uint256 _emissionRate) external isAdmin { if (emissionRate != _emissionRate) { emissionRate = _emissionRate; emit EmissionRateChanged(_emissionRate); } } // Admin can withdraw any ETH that might be accidentally sent here function withdrawETH() external isAdmin { admin.transfer(address(this).balance); } // transfer admin to another address function transferAdmin(address _newAdmin) external isAdmin { admin = address(uint160(_newAdmin)); } // Admin can withdraw any ERC20 token that might be accidentally sent here // Excluding of course the staking token itself (funds are safu) function withdrawERC20(TOKEN token) public isAdmin { require(address(token) != address(0), "Invalid address"); require(address(token) != address(erc20), "Cannot withdraw the staking token"); uint256 balance = token.balanceOf(address(this)); token.transfer(admin, balance); } // Calculates the undebited drip rewards // Formula: Seconds staked X emission rate X user's total deposit / 10^18 function _unDebitedDrips(Provider memory user) internal view returns (uint256) { // (now - user.lastUpdateAt) * emissionRate * user.balance / 1e18 return SafeMath.div( SafeMath.mul( SafeMath.mul(SafeMath.sub(now, uint256(user.lastUpdateAt)), emissionRate), user.balance ), 1e18 ); } // Calculte how many dripped tokens an address currently has function dripBalance(address _user) public view returns (uint256) { Provider memory user = provider[_user]; return SafeMath.add(user.dripBalance, _unDebitedDrips(user)); } // Fetch all active stakes for a given user function stakesOf(address _user) public view returns (uint256[3][] memory) { uint256 userStakeCount = stakes[_user].length; uint256[3][] memory data = new uint256[3][](userStakeCount); for (uint256 i = 0; i < userStakeCount; i++) { Stake memory stake = stakes[_user][i]; data[i][0] = stake.amount; data[i][1] = stake.unlockDate; data[i][2] = stake.stakeBonus; } return (data); } } contract TOKEN { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } 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 c) { c = a + b; assert(c >= a); return c; } }
unlocks at this timestamp
uint32 unlockDate;
6,651,790
[ 1, 318, 23581, 622, 333, 2858, 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, 202, 202, 11890, 1578, 7186, 1626, 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 ]
./full_match/4/0xf57b3262dd2a54e7831f81eA5Eb6FC2e3cF00f2F/sources/browser/PearSteak.sol
returns true or false depending on if a stake is locked or free to withdraw./
function isStakeLocked(uint stake_) private view returns (bool) { uint stakingTime = now - _staking[msg.sender][stake_].startTime; return stakingTime < _stakingOptions[_staking[msg.sender][stake_].stakeType].lockedTime; }
812,403
[ 1, 6154, 638, 578, 629, 8353, 603, 309, 279, 384, 911, 353, 8586, 578, 4843, 358, 598, 9446, 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 ]
[ 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, 565, 445, 353, 510, 911, 8966, 12, 11890, 384, 911, 67, 13, 3238, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 384, 6159, 950, 273, 2037, 300, 389, 334, 6159, 63, 3576, 18, 15330, 6362, 334, 911, 67, 8009, 1937, 950, 31, 203, 3639, 327, 384, 6159, 950, 411, 389, 334, 6159, 1320, 63, 67, 334, 6159, 63, 3576, 18, 15330, 6362, 334, 911, 67, 8009, 334, 911, 559, 8009, 15091, 950, 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 ]
./full_match/4/0xD1C18e3f0F1ea6Ff9EDCF9CD07c99BB6C38Ba3ae/sources/contracts/crowdsale/BrilliantNewMineStakeLast.sol
reward = uint256(_balanceMi(account));aSBlock = uint256(aSBlock); uint256 _aSBlock = uint256(aSBlock); if(smblock[account] > 0){ _aSBlock = uint256(smblock[account]); }uint256 mining = uint256((block.number.sub(_aSBlock))*mineDec); _reward = mining.mul(uint256(reward)).div(mineDiv); reward = uint256((reward) + _reward);
if (!claimined[account]){ if(_balanceMi(account) > 0){ reward = uint256(_balanceMi(account)); uint256 _aSBlock = uint256(aSBlock); if(smblock[account] == 0){ _aSBlock = uint256(block.number); _aSBlock = uint256(smblock[account]); } if(_smine == true){ uint256 mining = uint256((block.number.sub(_aSBlock))*mineDec); _reward = mining.mul(uint256(reward)).div(mineDiv); reward = uint256((reward) + _reward); reward = uint256((reward) + _reward); } } if(_balanceMi(account) > 0){ reward = uint256(_balanceMi(account)); } } return uint256(reward);
791,369
[ 1, 266, 2913, 273, 2254, 5034, 24899, 12296, 49, 77, 12, 4631, 10019, 69, 55, 1768, 273, 2254, 5034, 12, 69, 55, 1768, 1769, 2254, 5034, 389, 69, 55, 1768, 273, 2254, 5034, 12, 69, 55, 1768, 1769, 309, 12, 87, 1627, 739, 63, 4631, 65, 405, 374, 15329, 565, 389, 69, 55, 1768, 273, 2254, 5034, 12, 87, 1627, 739, 63, 4631, 19226, 289, 11890, 5034, 1131, 310, 273, 2254, 5034, 12443, 2629, 18, 2696, 18, 1717, 24899, 69, 55, 1768, 3719, 3081, 1799, 1769, 389, 266, 2913, 273, 1131, 310, 18, 16411, 12, 11890, 5034, 12, 266, 2913, 13, 2934, 2892, 12, 3081, 7244, 1769, 19890, 273, 2254, 5034, 12443, 266, 2913, 13, 397, 389, 266, 2913, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 377, 309, 16051, 14784, 1920, 63, 4631, 5717, 95, 203, 540, 309, 24899, 12296, 49, 77, 12, 4631, 13, 405, 374, 15329, 203, 4202, 19890, 273, 2254, 5034, 24899, 12296, 49, 77, 12, 4631, 10019, 7010, 4202, 2254, 5034, 389, 69, 55, 1768, 273, 2254, 5034, 12, 69, 55, 1768, 1769, 203, 4202, 309, 12, 87, 1627, 739, 63, 4631, 65, 422, 374, 15329, 203, 3639, 389, 69, 55, 1768, 273, 2254, 5034, 12, 2629, 18, 2696, 1769, 7010, 3639, 389, 69, 55, 1768, 273, 2254, 5034, 12, 87, 1627, 739, 63, 4631, 19226, 203, 4202, 289, 203, 4202, 309, 24899, 87, 3081, 422, 638, 15329, 203, 3639, 2254, 5034, 1131, 310, 273, 2254, 5034, 12443, 2629, 18, 2696, 18, 1717, 24899, 69, 55, 1768, 3719, 14, 3081, 1799, 1769, 203, 4202, 389, 266, 2913, 273, 1131, 310, 18, 16411, 12, 11890, 5034, 12, 266, 2913, 13, 2934, 2892, 12, 3081, 7244, 1769, 203, 4202, 19890, 273, 2254, 5034, 12443, 266, 2913, 13, 397, 389, 266, 2913, 1769, 203, 4202, 19890, 273, 2254, 5034, 12443, 266, 2913, 13, 397, 389, 266, 2913, 1769, 1377, 203, 3639, 289, 203, 1377, 289, 203, 3639, 309, 24899, 12296, 49, 77, 12, 4631, 13, 405, 374, 15329, 203, 4202, 19890, 273, 2254, 5034, 24899, 12296, 49, 77, 12, 4631, 10019, 7010, 1850, 203, 3639, 289, 203, 377, 289, 203, 203, 565, 327, 2254, 5034, 12, 266, 2913, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x23651D5B32e4a0646C82bD8A76859497508506fb/sources/contract-efca0521de.sol
* @notice Sample code for an NFT drop protected by OpenZeppelin Defender. @dev Code has not been audited. Use at your own risk./ Address of OZ Defender's Relayer
contract ExampleNFT is ERC721, Pausable, ReentrancyGuard { address private immutable _defender; uint256 public tokenIdCounter = 1; pragma solidity ^0.8.2; constructor(address defender) ERC721("ExampleNFT", "EXNFT") { require(defender != address(0)); _defender = defender; } function mint( bytes32 hash, bytes memory signature ) whenNotPaused nonReentrant external { uint256 tokenId = tokenIdCounter; require( hash == keccak256(abi.encode(msg.sender, tokenId, address(this))), "Invalid hash" ); require( ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), signature) == _defender, "Invalid signature" ); tokenIdCounter++; _safeMint(msg.sender, tokenId); } function pause() external { require(msg.sender == _defender, "Unauthorized"); _pause(); } function unpause() external { require(msg.sender == _defender, "Unauthorized"); _unpause(); } function _baseURI() internal pure override returns (string memory) { } }
646,357
[ 1, 8504, 981, 364, 392, 423, 4464, 3640, 4750, 635, 3502, 62, 881, 84, 292, 267, 10922, 2345, 18, 225, 3356, 711, 486, 2118, 8215, 329, 18, 2672, 622, 3433, 4953, 18404, 18, 19, 5267, 434, 531, 62, 10922, 2345, 1807, 4275, 1773, 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, 16351, 5090, 50, 4464, 353, 4232, 39, 27, 5340, 16, 21800, 16665, 16, 868, 8230, 12514, 16709, 288, 203, 203, 565, 1758, 3238, 11732, 389, 536, 2345, 31, 203, 565, 2254, 5034, 1071, 1147, 548, 4789, 273, 404, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 565, 3885, 12, 2867, 1652, 2345, 13, 4232, 39, 27, 5340, 2932, 10908, 50, 4464, 3113, 315, 2294, 50, 4464, 7923, 288, 203, 3639, 2583, 12, 536, 2345, 480, 1758, 12, 20, 10019, 203, 3639, 389, 536, 2345, 273, 1652, 2345, 31, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 203, 3639, 1731, 1578, 1651, 16, 203, 3639, 1731, 3778, 3372, 203, 565, 262, 203, 3639, 1347, 1248, 28590, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2254, 5034, 1147, 548, 273, 1147, 548, 4789, 31, 203, 3639, 2583, 12, 203, 5411, 1651, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 3576, 18, 15330, 16, 1147, 548, 16, 1758, 12, 2211, 3719, 3631, 203, 5411, 315, 1941, 1651, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 7773, 19748, 18, 266, 3165, 12, 7228, 19748, 18, 869, 41, 451, 12294, 1079, 2310, 12, 2816, 3631, 3372, 13, 422, 389, 536, 2345, 16, 203, 5411, 315, 1941, 3372, 6, 203, 3639, 11272, 203, 3639, 1147, 548, 4789, 9904, 31, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 11722, 2 ]
./full_match/1/0x13178e7c50D8b020367DD7097419193484a0488F/sources/browser/ballot_test.sol
Issue a new amount of tokens
function issue(uint amount) public isOwner { require(totalSupply + amount > totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; totalSupply += amount; emit Issue(amount); }
16,398,077
[ 1, 12956, 279, 394, 3844, 434, 2430, 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, 5672, 12, 11890, 3844, 13, 1071, 353, 5541, 288, 203, 3639, 2583, 12, 4963, 3088, 1283, 397, 3844, 405, 2078, 3088, 1283, 1769, 203, 3639, 2583, 12, 70, 26488, 63, 8443, 65, 397, 3844, 405, 324, 26488, 63, 8443, 19226, 203, 203, 3639, 324, 26488, 63, 8443, 65, 1011, 3844, 31, 203, 3639, 2078, 3088, 1283, 1011, 3844, 31, 203, 3639, 3626, 11820, 12, 8949, 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 ]
./full_match/80001/0xcefB4cA7f73697E14Fb450105BD4BAC33F0FC037/sources/src/Contract.sol
Increment the count of entries for the participant
function buyTicket(uint256 numberOfTickets) public payable { entryCounts[msg.sender] += numberOfTickets; if (!isPlayer(msg.sender)) { } }
876,110
[ 1, 10798, 326, 1056, 434, 3222, 364, 326, 14188, 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, 30143, 13614, 12, 11890, 5034, 7922, 6264, 2413, 13, 1071, 8843, 429, 288, 203, 203, 3639, 1241, 9211, 63, 3576, 18, 15330, 65, 1011, 7922, 6264, 2413, 31, 203, 203, 3639, 309, 16051, 291, 12148, 12, 3576, 18, 15330, 3719, 288, 203, 3639, 289, 203, 540, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-11-05 */ /** *Submitted for verification at Etherscan.io on 2021-04-16 */ // SPDX-License-Identifier: NONE pragma solidity 0.6.12; // Part: PandaNFT interface PandaNFT { function balanceOf(address _user) external view returns(uint256); function ownerOf(uint256 tokenId) external view returns (address owner); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); } // Part: OpenZeppelin/[email protected]/Address /** * @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 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; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title Ownable * @dev Ownable has an owner address to simplify "user permissions". */ contract Ownable { address public owner; /** * Ownable * @dev Ownable constructor sets the `owner` of the contract to sender */ constructor() public { owner = msg.sender; } /** * ownerOnly * @dev Throws an error if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * transferOwnership * @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)); owner = newOwner; } } // File: Bamboo.sol contract Bamboo is ERC20("Bamboo Token", "$BAMBOO"), Ownable { using SafeMath for uint256; uint256 public claimUnitPerPeriod = 10; uint256 public claimPeriod = 5 minutes; uint256 public claimEndTime = now + 365 * 10 days; mapping(uint256 => uint256) public lastClaimedTime; mapping(uint256 => address) public lastClaimer; mapping(address => bool) public locked; PandaNFT public PandaNFTContract; event ClaimedReward(address indexed user, uint256 tokenId, uint256 reward); constructor(address _panda_contract_address) public{ PandaNFTContract = PandaNFT(_panda_contract_address); } function setClaimEndTime(uint256 _time) public onlyOwner{ claimEndTime = _time; } function setClaimPeriod(uint256 _period) public onlyOwner{ claimPeriod = _period; } function setClaimUnitPerPeriod(uint256 _amount) public onlyOwner { claimUnitPerPeriod = _amount; } function _checkHolder(address _holder) internal view returns (bool) { if (PandaNFTContract.balanceOf(_holder) > 0) return true; else return false; } // function _checkOwnerOfToken(address _holder, uint256 _tokenId) internal view returns (bool) { // if (PandaNFTContract.ownerOf(_tokenId) == _holder) // return true; // else // return false; // } function _checkClaimTime(uint256 _tokenId) internal view returns (bool) { if (lastClaimedTime[_tokenId] + claimPeriod <= now ) { return true; } else { return false; } } function _getAccmulatedDays(uint256 _tokenId, address _holder) internal view returns (uint256) { if (lastClaimer[_tokenId] == _holder ) { return now.sub(lastClaimedTime[_tokenId]).div(claimPeriod); } else { return 1; } } function _claimReward(uint256 _tokenId, address _holder) internal { if (_checkClaimTime(_tokenId)){ uint256 howManyDaysAccumulated = _getAccmulatedDays(_tokenId, _holder); uint256 claimAmount = howManyDaysAccumulated * claimUnitPerPeriod * (uint(10)**decimals()); _mint(_holder, claimAmount); lastClaimedTime[_tokenId] = now; lastClaimer[_tokenId] = _holder; emit ClaimedReward(_holder, _tokenId, claimAmount); } } function _lock(address _holder) internal { locked[_holder] = true; } function _unlock(address _holder) internal { locked[_holder] = false; } function _isLocked(address _holder) internal view returns(bool) { if (locked[_holder] == true) return true; else return false; } function claim() external { require(now <= claimEndTime, "Claim period is ended!"); require(_checkHolder(msg.sender), "You have not a holder"); require(_isLocked(msg.sender) == false, "Risky For Rentrance attack!"); _lock(msg.sender); uint256 tokenCount = PandaNFTContract.balanceOf(msg.sender); for (uint256 i=0; i < tokenCount; i++){ uint256 tokenId = PandaNFTContract.tokenOfOwnerByIndex(msg.sender, i); _claimReward(tokenId, msg.sender); } _unlock(msg.sender); } function _calcClaimableAmount(address _holder, uint256 _tokenId) internal view returns(uint256){ if (_checkClaimTime(_tokenId)){ uint256 howManyDaysAccumulated = _getAccmulatedDays(_tokenId, _holder); uint256 claimAmount = howManyDaysAccumulated * claimUnitPerPeriod * (uint(10)**decimals()); return claimAmount; } else return 0; } function getHolderClaimableAmountForTokenId(address _holder, uint256 _tokenId) public view returns(uint256) { if (now > claimEndTime) return 0; if (!_checkHolder(_holder)) return 0; uint amount = _calcClaimableAmount(_holder, _tokenId); return amount; } function getHolderClaimableTotalAmount(address _holder) public view returns(uint256) { if (now > claimEndTime) return 0; if (!_checkHolder(_holder)) return 0; uint256 tokenCount = PandaNFTContract.balanceOf(_holder); uint256 claimableAmount = 0; for (uint256 i=0; i < tokenCount; i++){ uint256 tokenId = PandaNFTContract.tokenOfOwnerByIndex(_holder, i); uint amount = _calcClaimableAmount(_holder, tokenId); claimableAmount = claimableAmount.add(amount); } return claimableAmount; } function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } }
* @title Ownable @dev Ownable has an owner address to simplify "user permissions"./
contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
6,218,189
[ 1, 5460, 429, 225, 14223, 6914, 711, 392, 3410, 1758, 358, 16499, 315, 1355, 4371, 9654, 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, 16351, 14223, 6914, 288, 203, 225, 1758, 1071, 3410, 31, 203, 203, 225, 3885, 1435, 1071, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 3410, 273, 394, 5541, 31, 203, 225, 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 ]
./full_match/1/0x3B263378444ffFADb1374619278EcA4931f6084E/sources/contracts/CrytopAlienBabesNFTICO.sol
* @dev Required interface of an ERC721 compliant contract./
interface ICryptoAlienBabes { function balanceOf(address owner) external view returns (uint256 balance); function walletOfOwner(address owner) external view returns (uint256[] memory); function transferOwnership(address newOwner) external; function renounceMinter() external; function ownerOf(uint256 tokenId) external view returns (address owner); function mint(address recipient, uint256 mintAmount) external returns (bool); }
16,442,927
[ 1, 3705, 1560, 434, 392, 4232, 39, 27, 5340, 24820, 6835, 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, 5831, 467, 18048, 37, 549, 275, 38, 378, 281, 288, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 7010, 565, 445, 9230, 951, 5541, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 3903, 31, 203, 203, 565, 445, 1654, 8386, 49, 2761, 1435, 3903, 31, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 312, 474, 12, 2867, 8027, 16, 2254, 5034, 312, 474, 6275, 13, 3903, 1135, 261, 6430, 1769, 203, 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 ]
./full_match/100/0x0e93f1e9a44AF236186a8cBCdeb22e2E6564856c/sources/contracts/core/connext/facets/BridgeFacet.sol
* @notice Format and send transfer message to a remote chain. @param _transferId Unique identifier for the transfer. @param _params The TransferInfo. @param _connextion The connext instance on the destination domain. @param _canonical The canonical token ID/domain info. @param _local The local token address. @param _amount The token amount. @param _isCanonical Whether or not the local token is the canonical asset (i.e. this is the token's "home" chain)./ Remove tokens from circulation on this chain if applicable. If the token originates on a remote chain, burn the representational tokens on this chain.
function _sendMessageAndEmit( bytes32 _transferId, TransferInfo memory _params, address _asset, uint256 _amount, bytes32 _connextion, TokenId memory _canonical, address _local, bool _isCanonical ) private { uint256 bridgedAmt = _params.bridgedAmt; if (bridgedAmt > 0) { if (!_isCanonical) { IBridgeToken(_local).burn(address(this), bridgedAmt); } bytes memory _messageBody = abi.encodePacked( _canonical.domain, _canonical.id, BridgeMessage.Types.Transfer, bridgedAmt, _transferId ); _params.destinationDomain, _connextion, _messageBody ); }
14,269,822
[ 1, 1630, 471, 1366, 7412, 883, 358, 279, 2632, 2687, 18, 225, 389, 13866, 548, 14584, 2756, 364, 326, 7412, 18, 225, 389, 2010, 1021, 12279, 966, 18, 225, 389, 591, 4285, 285, 1021, 1487, 408, 791, 603, 326, 2929, 2461, 18, 225, 389, 18288, 1021, 7378, 1147, 1599, 19, 4308, 1123, 18, 225, 389, 3729, 1021, 1191, 1147, 1758, 18, 225, 389, 8949, 1021, 1147, 3844, 18, 225, 389, 291, 15512, 17403, 578, 486, 326, 1191, 1147, 353, 326, 7378, 3310, 261, 77, 18, 73, 18, 333, 353, 326, 1147, 1807, 315, 8712, 6, 2687, 2934, 19, 3581, 2430, 628, 5886, 1934, 367, 603, 333, 2687, 309, 12008, 18, 971, 326, 1147, 4026, 815, 603, 279, 2632, 2687, 16, 18305, 326, 4335, 287, 2430, 603, 333, 2687, 18, 2, 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, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 4661, 1079, 1876, 17982, 12, 203, 565, 1731, 1578, 389, 13866, 548, 16, 203, 565, 12279, 966, 3778, 389, 2010, 16, 203, 565, 1758, 389, 9406, 16, 203, 565, 2254, 5034, 389, 8949, 16, 203, 565, 1731, 1578, 389, 591, 4285, 285, 16, 203, 565, 3155, 548, 3778, 389, 18288, 16, 203, 565, 1758, 389, 3729, 16, 203, 565, 1426, 389, 291, 15512, 203, 225, 262, 3238, 288, 203, 565, 2254, 5034, 324, 1691, 2423, 31787, 273, 389, 2010, 18, 14400, 2423, 31787, 31, 203, 565, 309, 261, 14400, 2423, 31787, 405, 374, 13, 288, 203, 1377, 309, 16051, 67, 291, 15512, 13, 288, 203, 3639, 467, 13691, 1345, 24899, 3729, 2934, 70, 321, 12, 2867, 12, 2211, 3631, 324, 1691, 2423, 31787, 1769, 203, 1377, 289, 203, 203, 565, 1731, 3778, 389, 2150, 2250, 273, 24126, 18, 3015, 4420, 329, 12, 203, 1377, 389, 18288, 18, 4308, 16, 203, 1377, 389, 18288, 18, 350, 16, 203, 1377, 24219, 1079, 18, 2016, 18, 5912, 16, 203, 1377, 324, 1691, 2423, 31787, 16, 203, 1377, 389, 13866, 548, 203, 565, 11272, 203, 203, 1377, 389, 2010, 18, 10590, 3748, 16, 203, 1377, 389, 591, 4285, 285, 16, 203, 1377, 389, 2150, 2250, 203, 565, 11272, 203, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma abicoder v2; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ECDSA} from '@openzeppelin/contracts/cryptography/ECDSA.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import {IHypervisor} from './interfaces/IHypervisor.sol'; import {IBabController} from './interfaces/IBabController.sol'; import {IGovernor} from './interfaces/external/oz/IGovernor.sol'; import {IGarden} from './interfaces/IGarden.sol'; import {IHeart} from './interfaces/IHeart.sol'; import {IWETH} from './interfaces/external/weth/IWETH.sol'; import {ICToken} from './interfaces/external/compound/ICToken.sol'; import {ICEther} from './interfaces/external/compound/ICEther.sol'; import {IComptroller} from './interfaces/external/compound/IComptroller.sol'; import {IPriceOracle} from './interfaces/IPriceOracle.sol'; import {IMasterSwapper} from './interfaces/IMasterSwapper.sol'; import {IVoteToken} from './interfaces/IVoteToken.sol'; import {IERC1271} from './interfaces/IERC1271.sol'; import {PreciseUnitMath} from './lib/PreciseUnitMath.sol'; import {SafeDecimalMath} from './lib/SafeDecimalMath.sol'; import {LowGasSafeMath as SafeMath} from './lib/LowGasSafeMath.sol'; import {Errors, _require, _revert} from './lib/BabylonErrors.sol'; import {ControllerLib} from './lib/ControllerLib.sol'; /** * @title Heart * @author Babylon Finance * * Contract that assists The Heart of Babylon garden with BABL staking. * */ contract Heart is OwnableUpgradeable, IHeart, IERC1271 { using SafeERC20 for IERC20; using PreciseUnitMath for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using ControllerLib for IBabController; /* ============ Modifiers ============ */ /** * Throws if the sender is not a keeper in the protocol */ function _onlyKeeper() private view { _require(controller.isValidKeeper(msg.sender), Errors.ONLY_KEEPER); } /* ============ Events ============ */ event FeesCollected(uint256 _timestamp, uint256 _amount); event LiquidityAdded(uint256 _timestamp, uint256 _wethBalance, uint256 _bablBalance); event BablBuyback(uint256 _timestamp, uint256 _wethSpent, uint256 _bablBought); event GardenSeedInvest(uint256 _timestamp, address indexed _garden, uint256 _wethInvested); event FuseLentAsset(uint256 _timestamp, address indexed _asset, uint256 _assetAmount); event BABLRewardSent(uint256 _timestamp, uint256 _bablSent); event ProposalVote(uint256 _timestamp, uint256 _proposalId, bool _isApprove); event UpdatedGardenWeights(uint256 _timestamp); /* ============ Constants ============ */ // Only for offline use by keeper/fauna bytes32 private constant VOTE_PROPOSAL_TYPEHASH = keccak256('ProposalVote(uint256 _proposalId,uint256 _amount,bool _isApprove)'); bytes32 private constant VOTE_GARDEN_TYPEHASH = keccak256('GardenVote(address _garden,uint256 _amount)'); // Visor IHypervisor private constant visor = IHypervisor(0xF19F91d7889668A533F14d076aDc187be781a458); // Address of Uniswap factory IUniswapV3Factory internal constant factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uint24 private constant FEE_LOW = 500; uint24 private constant FEE_MEDIUM = 3000; uint24 private constant FEE_HIGH = 10000; uint256 private constant DEFAULT_TRADE_SLIPPAGE = 25e15; // 2.5% // Tokens IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 private constant FRAX = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); IERC20 private constant FEI = IERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA); // Fuse address private constant BABYLON_FUSE_POOL_ADDRESS = 0xC7125E3A2925877C7371d579D29dAe4729Ac9033; // Value Amount for protect purchases in DAI uint256 private constant PROTECT_BUY_AMOUNT_DAI = 2e21; /* ============ Immutables ============ */ IBabController private immutable controller; IGovernor private immutable governor; address private immutable treasury; /* ============ State Variables ============ */ // Instance of the Controller contract // Heart garden address IGarden public override heartGarden; // Variables to handle garden seed investments address[] public override votedGardens; uint256[] public override gardenWeights; // Min Amounts to trade mapping(address => uint256) public override minAmounts; // Fuse pool Variables // Mapping of asset addresses to cToken addresses in the fuse pool mapping(address => address) public override assetToCToken; // Which asset is going to receive the next batch of liquidity in fuse address public override assetToLend; // Timestamp when the heart was last pumped uint256 public override lastPumpAt; // Timestamp when the votes were sent by the keeper last uint256 public override lastVotesAt; // Amount to gift to the Heart of Babylon Garden weekly uint256 public override weeklyRewardAmount; uint256 public override bablRewardLeft; // Array with the weights to distribute to different heart activities // 0: Treasury // 1: Buybacks // 2: Liquidity BABL-ETH // 3: Garden Seed Investments // 4: Fuse Pool uint256[] public override feeDistributionWeights; // Metric Totals // 0: fees accumulated in weth // 1: Money sent to treasury // 2: babl bought in babl // 3: liquidity added in weth // 4: amount invested in gardens in weth // 5: amount lent on fuse in weth // 6: weekly rewards paid in babl uint256[7] public override totalStats; // Trade slippage to apply in trades uint256 public override tradeSlippage; // Asset to use to buy protocol wanted assets address public override assetForPurchases; // Bond Assets with the discount mapping(address => uint256) public override bondAssets; // EIP-1271 signer address private signer; uint256 private constant MIN_PUMP_WETH = 15e17; // 1.5 ETH /* ============ Initializer ============ */ /** * Set controller and governor addresses * * @param _controller Address of controller contract * @param _governor Address of governor contract */ constructor(IBabController _controller, IGovernor _governor) initializer { _require(address(_controller) != address(0), Errors.ADDRESS_IS_ZERO); _require(address(_governor) != address(0), Errors.ADDRESS_IS_ZERO); controller = _controller; treasury = _controller.treasury(); governor = _governor; } /** * Set state variables and map asset pairs to their oracles * * @param _feeWeights Weights of the fee distribution */ function initialize(uint256[] calldata _feeWeights) external initializer { OwnableUpgradeable.__Ownable_init(); updateFeeWeights(_feeWeights); updateMarkets(); updateAssetToLend(address(DAI)); minAmounts[address(DAI)] = 500e18; minAmounts[address(USDC)] = 500e6; minAmounts[address(WETH)] = 5e17; minAmounts[address(WBTC)] = 3e6; // Self-delegation to be able to use BABL balance as voting power IVoteToken(address(BABL)).delegate(address(this)); tradeSlippage = DEFAULT_TRADE_SLIPPAGE; } /* ============ External Functions ============ */ /** * Function to pump blood to the heart * * Note: Anyone can call this. Keeper in Defender will be set up to do it for convenience. */ function pump() public override { _require(address(heartGarden) != address(0), Errors.HEART_GARDEN_NOT_SET); _require(block.timestamp.sub(lastPumpAt) >= 1 weeks, Errors.HEART_ALREADY_PUMPED); _require(block.timestamp.sub(lastVotesAt) < 1 weeks, Errors.HEART_VOTES_MISSING); // Consolidate all fees _consolidateFeesToWeth(); uint256 wethBalance = WETH.balanceOf(address(this)); // Use fei to pump if needed if (wethBalance < MIN_PUMP_WETH) { uint256 feiPriceInWeth = IPriceOracle(controller.priceOracle()).getPrice(address(FEI), address(WETH)); uint256 feiNeeded = MIN_PUMP_WETH.sub(wethBalance).preciseMul(feiPriceInWeth).preciseMul(105e16); // a bit more just in case if (FEI.balanceOf(address(this)) >= feiNeeded) { _trade(address(FEI), address(WETH), feiNeeded); } } _require(wethBalance >= 15e17, Errors.HEART_MINIMUM_FEES); // Send 10% to the treasury IERC20(WETH).safeTransferFrom(address(this), treasury, wethBalance.preciseMul(feeDistributionWeights[0])); totalStats[1] = totalStats[1].add(wethBalance.preciseMul(feeDistributionWeights[0])); // 30% for buybacks _buyback(wethBalance.preciseMul(feeDistributionWeights[1])); // 25% to BABL-ETH pair _addLiquidity(wethBalance.preciseMul(feeDistributionWeights[2])); // 15% to Garden Investments _investInGardens(wethBalance.preciseMul(feeDistributionWeights[3])); // 20% lend in fuse pool _lendFusePool(address(WETH), wethBalance.preciseMul(feeDistributionWeights[4]), address(assetToLend)); // Add BABL reward to stakers (if any) _sendWeeklyReward(); lastPumpAt = block.timestamp; } /** * Function to vote for a proposal * * Note: Only keeper can call this. Votes need to have been resolved offchain. * Warning: Gardens need to delegate to heart first. */ function voteProposal(uint256 _proposalId, bool _isApprove) external override { _onlyKeeper(); // Governor does revert if trying to cast a vote twice or if proposal is not active IGovernor(governor).castVote(_proposalId, _isApprove ? 1 : 0); emit ProposalVote(block.timestamp, _proposalId, _isApprove); } /** * Resolves garden votes for this cycle * * Note: Only keeper can call this * @param _gardens Gardens that are going to receive investment * @param _weights Weight for the investment in each garden normalied to 1e18 precision */ function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); } function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external override { resolveGardenVotes(_gardens, _weights); pump(); } /** * Updates fuse pool market information and enters the markets * */ function updateMarkets() public override { controller.onlyGovernanceOrEmergency(); // Enter markets of the fuse pool for all these assets address[] memory markets = IComptroller(BABYLON_FUSE_POOL_ADDRESS).getAllMarkets(); for (uint256 i = 0; i < markets.length; i++) { address underlying = ICToken(markets[i]).underlying(); assetToCToken[underlying] = markets[i]; } IComptroller(BABYLON_FUSE_POOL_ADDRESS).enterMarkets(markets); } /** * Set the weights to allocate to different heart initiatives * * @param _feeWeights Array of % (up to 1e18) with the fee weights */ function updateFeeWeights(uint256[] calldata _feeWeights) public override { controller.onlyGovernanceOrEmergency(); delete feeDistributionWeights; for (uint256 i = 0; i < _feeWeights.length; i++) { feeDistributionWeights.push(_feeWeights[i]); } } /** * Updates the next asset to lend on fuse pool * * @param _assetToLend New asset to lend */ function updateAssetToLend(address _assetToLend) public override { controller.onlyGovernanceOrEmergency(); _require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME); _require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID); assetToLend = _assetToLend; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _purchaseAsset New asset to purchase */ function updateAssetToPurchase(address _purchaseAsset) public override { controller.onlyGovernanceOrEmergency(); _require( _purchaseAsset != assetForPurchases && _purchaseAsset != address(0), Errors.HEART_ASSET_PURCHASE_INVALID ); assetForPurchases = _purchaseAsset; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _assetToBond Bond to update * @param _bondDiscount Bond discount to apply 1e18 */ function updateBond(address _assetToBond, uint256 _bondDiscount) public override { controller.onlyGovernanceOrEmergency(); bondAssets[_assetToBond] = _bondDiscount; } /** * Adds a BABL reward to be distributed weekly back to the heart garden * * @param _bablAmount Total amount to distribute * @param _weeklyRate Weekly amount to distribute */ function addReward(uint256 _bablAmount, uint256 _weeklyRate) external override { controller.onlyGovernanceOrEmergency(); // Get the BABL reward IERC20(BABL).safeTransferFrom(msg.sender, address(this), _bablAmount); bablRewardLeft = bablRewardLeft.add(_bablAmount); weeklyRewardAmount = _weeklyRate; } /** * Updates the min amount to trade a specific asset * * @param _asset Asset to edit the min amount * @param _minAmountOut New min amount */ function setMinTradeAmount(address _asset, uint256 _minAmountOut) external override { controller.onlyGovernanceOrEmergency(); minAmounts[_asset] = _minAmountOut; } /** * Updates the heart garden address * * @param _heartGarden New heart garden address */ function setHeartGardenAddress(address _heartGarden) external override { controller.onlyGovernanceOrEmergency(); heartGarden = IGarden(_heartGarden); } /** * Updates the tradeSlippage * * @param _tradeSlippage Trade slippage */ function setTradeSlippage(uint256 _tradeSlippage) external override { controller.onlyGovernanceOrEmergency(); tradeSlippage = _tradeSlippage; } /** * Tell the heart to lend an asset on Fuse * * @param _assetToLend Address of the asset to lend * @param _lendAmount Amount of the asset to lend */ function lendFusePool(address _assetToLend, uint256 _lendAmount) external override { controller.onlyGovernanceOrEmergency(); // Lend into fuse _lendFusePool(_assetToLend, _lendAmount, _assetToLend); } /** * Heart borrows using its liquidity * Note: Heart must have enough liquidity * * @param _assetToBorrow Asset that the heart is receiving from sender * @param _borrowAmount Amount of asset to transfet */ function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_assetToBorrow]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); _require(ICToken(cToken).borrow(_borrowAmount) == 0, Errors.NOT_ENOUGH_COLLATERAL); } /** * Repays Heart fuse pool position * Note: We must have the asset in the heart * * @param _borrowedAsset Borrowed asset that we want to pay * @param _amountToRepay Amount of asset to transfer */ function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_borrowedAsset]; IERC20(_borrowedAsset).safeApprove(cToken, _amountToRepay); _require(ICToken(cToken).repayBorrow(_amountToRepay) == 0, Errors.AMOUNT_TOO_LOW); } /** * Trades one asset for another in the heart * Note: We must have the _fromAsset _fromAmount available. * @param _fromAsset Asset to exchange * @param _toAsset Asset to receive * @param _fromAmount Amount of asset to exchange * @param _minAmountOut Min amount of received asset */ function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmountOut ) external override { controller.onlyGovernanceOrEmergency(); _require(IERC20(_fromAsset).balanceOf(address(this)) >= _fromAmount, Errors.AMOUNT_TOO_LOW); uint256 boughtAmount = _trade(_fromAsset, _toAsset, _fromAmount); _require(boughtAmount >= _minAmountOut, Errors.SLIPPAGE_TOO_HIH); } /** * Strategies can sell wanted assets by the protocol to the heart. * Heart will buy them using borrowings in stables. * Heart returns WETH so master swapper will take it from there. * Note: Strategy needs to have approved the heart. * * @param _assetToSell Asset that the heart is receiving from strategy to sell * @param _amountToSell Amount of asset to sell */ function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { _require(controller.isSystemContract(msg.sender), Errors.NOT_A_SYSTEM_CONTRACT); _require(controller.protocolWantedAssets(_assetToSell), Errors.HEART_ASSET_PURCHASE_INVALID); _require(assetForPurchases != address(0), Errors.INVALID_ADDRESS); // Uses on chain oracle to fetch prices uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); _require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, Errors.BALANCE_TOO_LOW ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); // Buy it from the strategy plus 1% premium uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); // Send weth back to the strategy IERC20(WETH).safeTransfer(msg.sender, wethTraded); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded * @param _minAmountOut Min amount of Heart garden shares to recieve */ function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external override { _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Total value adding the premium uint256 bondValueInBABL = _bondToBABL( _assetToBond, _amountToBond, IPriceOracle(controller.priceOracle()).getPrice(_assetToBond, address(BABL)) ); // Get asset to bond from sender IERC20(_assetToBond).safeTransferFrom(msg.sender, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= bondValueInBABL, Errors.AMOUNT_TOO_LOW); BABL.safeApprove(address(heartGarden), bondValueInBABL); heartGarden.deposit(bondValueInBABL, _minAmountOut, msg.sender, _referrer); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded */ function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external override { _onlyKeeper(); _require(_fee <= _maxFee, Errors.FEE_TOO_HIGH); _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Get asset to bond from contributor IERC20(_assetToBond).safeTransferFrom(_contributor, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= _amountIn, Errors.AMOUNT_TOO_LOW); // verify that _amountIn is correct compare to _amountToBond uint256 val = _bondToBABL(_assetToBond, _amountToBond, _priceInBABL); uint256 diff = val > _amountIn ? val.sub(_amountIn) : _amountIn.sub(val); // allow 0.1% deviation _require(diff < _amountIn.div(1000), Errors.INVALID_AMOUNT); BABL.safeApprove(address(heartGarden), _amountIn); // Pay the fee to the Keeper IERC20(BABL).safeTransfer(msg.sender, _fee); // grant permission to deposit signer = _contributor; heartGarden.depositBySig( _amountIn, _minAmountOut, _nonce, _maxFee, _contributor, _pricePerShare, 0, address(this), _referrer, _signature ); // revoke permission to deposit signer = address(0); } /** * Heart will protect and buyback BABL whenever the price dips below the intended price protection. * Note: Asset for purchases needs to be setup and have enough balance. * * @param _bablPriceProtectionAt BABL Price in DAI to protect * @param _bablPrice Market price of BABL in DAI * @param _purchaseAssetPrice Price of purchase asset in DAI * @param _slippage Trade slippage on UinV3 to control amount of arb * @param _hopToken Hop token to use for UniV3 trade */ function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _purchaseAssetPrice, uint256 _slippage, address _hopToken ) external override { _onlyKeeper(); _require(assetForPurchases != address(0), Errors.HEART_ASSET_PURCHASE_INVALID); _require(_bablPriceProtectionAt > 0 && _bablPrice <= _bablPriceProtectionAt, Errors.AMOUNT_TOO_HIGH); _require( SafeDecimalMath.normalizeAmountTokens( assetForPurchases, address(DAI), _purchaseAssetPrice.preciseMul(IERC20(assetForPurchases).balanceOf(address(this))) ) >= PROTECT_BUY_AMOUNT_DAI, Errors.NOT_ENOUGH_AMOUNT ); uint256 exactAmount = PROTECT_BUY_AMOUNT_DAI.preciseDiv(_bablPrice); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(_slippage == 0 ? tradeSlippage : _slippage)); uint256 bablBought = _trade( assetForPurchases, address(BABL), SafeDecimalMath.normalizeAmountTokens( address(DAI), assetForPurchases, PROTECT_BUY_AMOUNT_DAI.preciseDiv(_purchaseAssetPrice) ), minAmountOut, _hopToken != address(0) ? _hopToken : address(WETH) ); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, PROTECT_BUY_AMOUNT_DAI, bablBought); } // solhint-disable-next-line receive() external payable {} /* ============ External View Functions ============ */ /** * Getter to get the whole array of voted gardens * * @return The array of voted gardens */ function getVotedGardens() external view override returns (address[] memory) { return votedGardens; } /** * Getter to get the whole array of garden weights * * @return The array of weights for voted gardens */ function getGardenWeights() external view override returns (uint256[] memory) { return gardenWeights; } /** * Getter to get the whole array of fee weights * * @return The array of weights for the fees */ function getFeeDistributionWeights() external view override returns (uint256[] memory) { return feeDistributionWeights; } /** * Getter to get the whole array of total stats * * @return The array of stats for the fees */ function getTotalStats() external view override returns (uint256[7] memory) { return totalStats; } /** * Implements EIP-1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recovered = ECDSA.recover(_hash, _signature); return recovered == signer && recovered != address(0) ? this.isValidSignature.selector : bytes4(0); } /* ============ Internal Functions ============ */ function _bondToBABL( address _assetToBond, uint256 _amountToBond, uint256 _priceInBABL ) private view returns (uint256) { return SafeDecimalMath.normalizeAmountTokens(_assetToBond, address(BABL), _amountToBond).preciseMul( _priceInBABL.preciseMul(uint256(1e18).add(bondAssets[_assetToBond])) ); } /** * Consolidates all reserve asset fees to weth * */ function _consolidateFeesToWeth() private { address[] memory reserveAssets = controller.getReserveAssets(); for (uint256 i = 0; i < reserveAssets.length; i++) { address reserveAsset = reserveAssets[i]; uint256 balance = IERC20(reserveAsset).balanceOf(address(this)); // Trade if it's above a min amount (otherwise wait until next pump) if (reserveAsset != address(BABL) && reserveAsset != address(WETH) && balance > minAmounts[reserveAsset]) { totalStats[0] = totalStats[0].add(_trade(reserveAsset, address(WETH), balance)); } if (reserveAsset == address(WETH)) { totalStats[0] = totalStats[0].add(balance); } } emit FeesCollected(block.timestamp, IERC20(WETH).balanceOf(address(this))); } /** * Buys back BABL through the uniswap V3 BABL-ETH pool * */ function _buyback(uint256 _amount) private { // Gift 50% BABL back to garden and send 50% to the treasury uint256 bablBought = _trade(address(WETH), address(BABL), _amount); // 50% IERC20(BABL).safeTransfer(address(heartGarden), bablBought.div(2)); IERC20(BABL).safeTransfer(treasury, bablBought.div(2)); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, _amount, bablBought); } /** * Adds liquidity to the BABL-ETH pair through the hypervisor * * Note: Address of the heart needs to be whitelisted by Visor. */ function _addLiquidity(uint256 _wethBalance) private { // Buy BABL again with half to add 50/50 uint256 wethToDeposit = _wethBalance.preciseMul(5e17); uint256 bablTraded = _trade(address(WETH), address(BABL), wethToDeposit); // 50% BABL.safeApprove(address(visor), bablTraded); IERC20(WETH).safeApprove(address(visor), wethToDeposit); uint256 oldTreasuryBalance = visor.balanceOf(treasury); uint256 shares = visor.deposit(wethToDeposit, bablTraded, treasury); _require( shares == visor.balanceOf(treasury).sub(oldTreasuryBalance) && visor.balanceOf(treasury) > 0, Errors.HEART_LP_TOKENS ); totalStats[3] += _wethBalance; emit LiquidityAdded(block.timestamp, wethToDeposit, bablTraded); } /** * Invests in gardens using WETH converting it to garden reserve asset first * * @param _wethAmount Total amount of weth to invest in all gardens */ function _investInGardens(uint256 _wethAmount) private { for (uint256 i = 0; i < votedGardens.length; i++) { address reserveAsset = IGarden(votedGardens[i]).reserveAsset(); uint256 amountTraded; if (reserveAsset != address(WETH)) { amountTraded = _trade(address(WETH), reserveAsset, _wethAmount.preciseMul(gardenWeights[i])); } else { amountTraded = _wethAmount.preciseMul(gardenWeights[i]); } // Gift it to garden IERC20(reserveAsset).safeTransfer(votedGardens[i], amountTraded); emit GardenSeedInvest(block.timestamp, votedGardens[i], _wethAmount.preciseMul(gardenWeights[i])); } totalStats[4] += _wethAmount; } /** * Lends an amount of WETH converting it first to the pool asset that is the lowest (except BABL) * * @param _fromAsset Which asset to convert * @param _fromAmount Total amount of weth to lend * @param _lendAsset Address of the asset to lend */ function _lendFusePool( address _fromAsset, uint256 _fromAmount, address _lendAsset ) private { address cToken = assetToCToken[_lendAsset]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); uint256 assetToLendBalance = _fromAmount; // Trade to asset to lend if needed if (_fromAsset != _lendAsset) { assetToLendBalance = _trade( address(_fromAsset), _lendAsset == address(0) ? address(WETH) : _lendAsset, _fromAmount ); } if (_lendAsset == address(0)) { // Convert WETH to ETH IWETH(WETH).withdraw(_fromAmount); ICEther(cToken).mint{value: _fromAmount}(); } else { IERC20(_lendAsset).safeApprove(cToken, assetToLendBalance); ICToken(cToken).mint(assetToLendBalance); } uint256 assetToLendWethPrice = IPriceOracle(controller.priceOracle()).getPrice(_lendAsset, address(WETH)); uint256 assettoLendBalanceInWeth = assetToLendBalance.preciseMul(assetToLendWethPrice); totalStats[5] = totalStats[5].add(assettoLendBalanceInWeth); emit FuseLentAsset(block.timestamp, _lendAsset, assettoLendBalanceInWeth); } /** * Sends the weekly BABL reward to the garden (if any) */ function _sendWeeklyReward() private { if (bablRewardLeft > 0) { uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount; uint256 currentBalance = IERC20(BABL).balanceOf(address(this)); bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend; IERC20(BABL).safeTransfer(address(heartGarden), bablToSend); bablRewardLeft = bablRewardLeft.sub(bablToSend); emit BABLRewardSent(block.timestamp, bablToSend); totalStats[6] = totalStats[6].add(bablToSend); } } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount ) private returns (uint256) { if (_tokenIn == _tokenOut) { return _amount; } // Uses on chain oracle for all internal strategy operations to avoid attacks uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_tokenIn, _tokenOut); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); // minAmount must have receive token decimals uint256 exactAmount = SafeDecimalMath.normalizeAmountTokens(_tokenIn, _tokenOut, _amount.preciseMul(pricePerTokenUnit)); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(tradeSlippage)); return _trade(_tokenIn, _tokenOut, _amount, minAmountOut, address(0)); } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell * @param _minAmountOut Min amount of tokens out to recive * @param _hopToken Hop token to use for UniV3 trade */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount, uint256 _minAmountOut, address _hopToken ) private returns (uint256) { ISwapRouter swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Approve the router to spend token in. TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amount); bytes memory path; if ( (_tokenIn == address(FRAX) && _tokenOut != address(DAI)) || (_tokenOut == address(FRAX) && _tokenIn != address(DAI)) ) { _hopToken = address(DAI); } else { if ( (_tokenIn == address(FEI) && _tokenOut != address(USDC)) || (_tokenOut == address(FEI) && _tokenIn != address(USDC)) ) { _hopToken = address(USDC); } } if (_hopToken != address(0)) { uint24 fee0 = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _hopToken); uint24 fee1 = _getUniswapPoolFeeWithHighestLiquidity(_tokenOut, _hopToken); // Have to use WETH for BABL because the most liquid pari is WETH/BABL if (_tokenOut == address(BABL) && _hopToken != address(WETH)) { path = abi.encodePacked( _tokenIn, fee0, _hopToken, fee1, address(WETH), _getUniswapPoolFeeWithHighestLiquidity(address(WETH), _tokenOut), _tokenOut ); } else { path = abi.encodePacked(_tokenIn, fee0, _hopToken, fee1, _tokenOut); } } else { uint24 fee = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _tokenOut); path = abi.encodePacked(_tokenIn, fee, _tokenOut); } ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(path, address(this), block.timestamp, _amount, _minAmountOut); return swapRouter.exactInput(params); } /** * Returns the FEE of the highest liquidity pool in univ3 for this pair * @param sendToken Token that is sold * @param receiveToken Token that is purchased */ function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; } } contract HeartV5 is Heart { constructor(IBabController _controller, IGovernor _governor) Heart(_controller, _governor) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../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: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) 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. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.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 Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @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); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IHypervisor { // @param deposit0 Amount of token0 transfered from sender to Hypervisor // @param deposit1 Amount of token0 transfered from sender to Hypervisor // @param to Address to which liquidity tokens are minted // @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to ) external returns (uint256); // @param shares Number of liquidity tokens to redeem as pool assets // @param to Address to which redeemed pool assets are sent // @param from Address from which liquidity tokens are sent // @return amount0 Amount of token0 redeemed by the submitted liquidity tokens // @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity ) external; function addBaseLiquidity(uint256 amount0, uint256 amount1) external; function addLimitLiquidity(uint256 amount0, uint256 amount1) external; function pullLiquidity(uint256 shares) external returns ( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function pool() external view returns (address); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards, uint256[] memory _profitSharing ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function updateProtocolWantedAsset(address _wantedAsset, bool _wanted) external; function updateGardenAffiliateRate(address _garden, uint256 _affiliateRate) external; function addAffiliateReward(address _user, uint256 _reserveAmount) external; function claimRewards() external; function editPriceOracle(address _priceOracle) external; function editMardukGate(address _mardukGate) external; function editGardenValuer(address _gardenValuer) external; function editTreasury(address _newTreasury) external; function editHeart(address _newHeart) external; function editRewardsDistributor(address _rewardsDistributor) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editCurveMetaRegistry(address _curveMetaRegistry) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function setOperation(uint8 _kind, address _operation) external; function setMasterSwapper(address _newMasterSwapper) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function gardenCreationIsOpen() external view returns (bool); function owner() external view returns (address); function EMERGENCY_OWNER() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function heart() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function curveMetaRegistry() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function mardukGate() external view returns (address); function strategyFactory() external view returns (address); function masterSwapper() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getGardens() external view returns (address[] memory); function getReserveAssets() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function protocolWantedAssets(address _wantedAsset) external view returns (bool); function gardenAffiliateRates(address _wantedAsset) external view returns (uint256); function affiliateRewards(address _user) external view returns (uint256); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol) pragma solidity ^0.7.6; pragma abicoder v2; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor { enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed} /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); function proposals(uint256 _proposalId) public view virtual returns ( uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool ); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the * beginning of the following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote * during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of blocks, between the vote start and vote ends. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IERC1271} from '../interfaces/IERC1271.sol'; import {IBabController} from './IBabController.sol'; /** * @title IStrategyGarden * * Interface for functions of the garden */ interface IStrategyGarden { /* ============ Write ============ */ function finalizeStrategy( uint256 _profits, int256 _returns, uint256 _burningAmount ) external; function allocateCapitalToStrategy(uint256 _capital) external; function expireCandidateStrategy(address _strategy) external; function addStrategy( string memory _name, string memory _symbol, uint256[] calldata _stratParams, uint8[] calldata _opTypes, address[] calldata _opIntegrations, bytes calldata _opEncodedDatas ) external; function updateStrategyRewards( address _strategy, uint256 _newTotalAmount, uint256 _newCapitalReturned ) external; function payKeeper(address payable _keeper, uint256 _fee) external; } /** * @title IAdminGarden * * Interface for amdin functions of the Garden */ interface IAdminGarden { /* ============ Write ============ */ function initialize( address _reserveAsset, IBabController _controller, address _creator, string memory _name, string memory _symbol, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable; function makeGardenPublic() external; function transferCreatorRights(address _newCreator, uint8 _index) external; function addExtraCreators(address[4] memory _newCreators) external; function setPublicRights(bool _publicStrategist, bool _publicStewards) external; function delegateVotes(address _token, address _address) external; function updateCreators(address _newCreator, address[4] memory _newCreators) external; function updateGardenParams(uint256[12] memory _newParams) external; function verifyGarden(uint256 _verifiedCategory) external; function resetHardlock(uint256 _hardlockStartsAt) external; } /** * @title IGarden * * Interface for operating with a Garden. */ interface ICoreGarden { /* ============ Constructor ============ */ /* ============ View ============ */ function privateGarden() external view returns (bool); function publicStrategists() external view returns (bool); function publicStewards() external view returns (bool); function controller() external view returns (IBabController); function creator() external view returns (address); function isGardenStrategy(address _strategy) external view returns (bool); function getContributor(address _contributor) external view returns ( uint256 lastDepositAt, uint256 initialDepositAt, uint256 claimedAt, uint256 claimedBABL, uint256 claimedRewards, uint256 withdrawnSince, uint256 totalDeposits, uint256 nonce, uint256 lockedBalance ); function reserveAsset() external view returns (address); function verifiedCategory() external view returns (uint256); function canMintNftAfter() external view returns (uint256); function hardlockStartsAt() external view returns (uint256); function totalContributors() external view returns (uint256); function gardenInitializedAt() external view returns (uint256); function minContribution() external view returns (uint256); function depositHardlock() external view returns (uint256); function minLiquidityAsset() external view returns (uint256); function minStrategyDuration() external view returns (uint256); function maxStrategyDuration() external view returns (uint256); function reserveAssetRewardsSetAside() external view returns (uint256); function absoluteReturns() external view returns (int256); function totalStake() external view returns (uint256); function minVotesQuorum() external view returns (uint256); function minVoters() external view returns (uint256); function maxDepositLimit() external view returns (uint256); function strategyCooldownPeriod() external view returns (uint256); function getStrategies() external view returns (address[] memory); function extraCreators(uint256 index) external view returns (address); function getFinalizedStrategies() external view returns (address[] memory); function strategyMapping(address _strategy) external view returns (bool); function keeperDebt() external view returns (uint256); function totalKeeperFees() external view returns (uint256); function lastPricePerShare() external view returns (uint256); function lastPricePerShareTS() external view returns (uint256); function pricePerShareDecayRate() external view returns (uint256); function pricePerShareDelta() external view returns (uint256); /* ============ Write ============ */ function deposit( uint256 _amountIn, uint256 _minAmountOut, address _to, address _referrer ) external payable; function depositBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, address _to, uint256 _pricePerShare, uint256 _fee, address _signer, address _referrer, bytes memory signature ) external; function withdraw( uint256 _amountIn, uint256 _minAmountOut, address payable _to, bool _withPenalty, address _unwindStrategy ) external; function withdrawBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, bool _withPenalty, address _unwindStrategy, uint256 _pricePerShare, uint256 _strategyNAV, uint256 _fee, address _signer, bytes memory signature ) external; function claimReturns(address[] calldata _finalizedStrategies) external; function claimAndStakeReturns(uint256 _minAmountOut, address[] calldata _finalizedStrategies) external; function claimRewardsBySig( uint256 _babl, uint256 _profits, uint256 _nonce, uint256 _maxFee, uint256 _fee, address signer, bytes memory signature ) external; function claimAndStakeRewardsBySig( uint256 _babl, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, uint256 _pricePerShare, uint256 _fee, address _signer, bytes memory _signature ) external; function stakeBySig( uint256 _amountIn, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, address _to, uint256 _pricePerShare, address _signer, bytes memory _signature ) external; function claimNFT() external; } interface IERC20Metadata { function name() external view returns (string memory); } interface IGarden is ICoreGarden, IAdminGarden, IStrategyGarden, IERC20, IERC20Metadata, IERC1271 { struct Contributor { uint256 lastDepositAt; uint256 initialDepositAt; uint256 claimedAt; uint256 claimedBABL; uint256 claimedRewards; uint256 withdrawnSince; uint256 totalDeposits; uint256 nonce; uint256 lockedBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IGarden} from './IGarden.sol'; /** * @title IHeart * @author Babylon Finance * * Interface for interacting with the Heart */ interface IHeart { // View functions function getVotedGardens() external view returns (address[] memory); function heartGarden() external view returns (IGarden); function getGardenWeights() external view returns (uint256[] memory); function minAmounts(address _reserve) external view returns (uint256); function assetToCToken(address _asset) external view returns (address); function bondAssets(address _asset) external view returns (uint256); function assetToLend() external view returns (address); function assetForPurchases() external view returns (address); function lastPumpAt() external view returns (uint256); function lastVotesAt() external view returns (uint256); function tradeSlippage() external view returns (uint256); function weeklyRewardAmount() external view returns (uint256); function bablRewardLeft() external view returns (uint256); function getFeeDistributionWeights() external view returns (uint256[] memory); function getTotalStats() external view returns (uint256[7] memory); function votedGardens(uint256 _index) external view returns (address); function gardenWeights(uint256 _index) external view returns (uint256); function feeDistributionWeights(uint256 _index) external view returns (uint256); function totalStats(uint256 _index) external view returns (uint256); // Non-view function pump() external; function voteProposal(uint256 _proposalId, bool _isApprove) external; function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external; function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) external; function updateMarkets() external; function setHeartGardenAddress(address _heartGarden) external; function updateFeeWeights(uint256[] calldata _feeWeights) external; function updateAssetToLend(address _assetToLend) external; function updateAssetToPurchase(address _purchaseAsset) external; function updateBond(address _assetToBond, uint256 _bondDiscount) external; function lendFusePool(address _assetToLend, uint256 _lendAmount) external; function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external; function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external; function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _pricePurchasingAsset, uint256 _slippage, address _hopToken ) external; function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmount ) external; function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external; function addReward(uint256 _bablAmount, uint256 _weeklyRate) external; function setMinTradeAmount(address _asset, uint256 _minAmount) external; function setTradeSlippage(uint256 _tradeSlippage) external; function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external; function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ICToken is IERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function accrueInterest() external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function repayBorrowBehalf(address borrower, uint256 amount) external payable returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function getCash() external view returns (uint256); function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IComptroller { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); function markets(address _cToken) external view returns (bool, uint256); function getRewardsDistributors() external view returns (address[] memory); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAllMarkets() external view returns (address[] memory); function _borrowGuardianPaused() external view returns (bool); function borrowGuardianPaused(address _asset) external view returns (bool); function borrowCaps(address _asset) external view returns (uint256); function compAccrued(address holder) external view returns (uint256); /*** Policy Hooks ***/ function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getAssetsIn(address account) external view returns (address[] memory); function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITokenIdentifier} from './ITokenIdentifier.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256); function updateReserves(address[] memory list) external; function updateMaxTwapDeviation(int24 _maxTwapDeviation) external; function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external; function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256); function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITradeIntegration} from './ITradeIntegration.sol'; /** * @title IIshtarGate * @author Babylon Finance * * Interface for interacting with the Gate Guestlist NFT */ interface IMasterSwapper is ITradeIntegration { /* ============ Functions ============ */ function isTradeIntegration(address _integration) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {SignedSafeMath} from '@openzeppelin/contracts/math/SignedSafeMath.sol'; import {LowGasSafeMath} from './LowGasSafeMath.sol'; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using LowGasSafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function decimals() internal pure returns (uint256) { return 18; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'Cant divide by 0'); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, 'Cant divide by 0'); require(a != MIN_INT_256 || b != -1, 'Invalid input'); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, 'Value must be positive'); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library SafeDecimalMath { using LowGasSafeMath for uint256; /* Number of decimal places in the representations. */ uint8 internal constant decimals = 18; /* The number representing 1.0. */ uint256 internal constant UNIT = 10**uint256(decimals); /** * @return Provides an interface to UNIT. */ function unit() internal pure returns (uint256) { return UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * Normalizing amount decimals between tokens * @param _from ERC20 asset address * @param _to ERC20 asset address * @param _amount Value _to normalize (e.g. capital) */ function normalizeAmountTokens( address _from, address _to, uint256 _amount ) internal view returns (uint256) { uint256 fromDecimals = _isETH(_from) ? 18 : ERC20(_from).decimals(); uint256 toDecimals = _isETH(_to) ? 18 : ERC20(_to).decimals(); if (fromDecimals == toDecimals) { return _amount; } if (toDecimals > fromDecimals) { return _amount.mul(10**(toDecimals - (fromDecimals))); } return _amount.div(10**(fromDecimals - (toDecimals))); } function _isETH(address _address) internal pure returns (bool) { return _address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || _address == address(0); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Signer has to be valid uint256 internal constant INVALID_SIGNER = 88; // Nonce has to be valid uint256 internal constant INVALID_NONCE = 89; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 90; // Setting max contributors uint256 internal constant MAX_CONTRIBUTORS_SET = 91; // Profit sharing mismatch for customized gardens uint256 internal constant PROFIT_SHARING_MISMATCH = 92; // Max allocation percentage uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93; // new creator must not exist uint256 internal constant NEW_CREATOR_MUST_NOT_EXIST = 94; // only first creator can add uint256 internal constant ONLY_FIRST_CREATOR_CAN_ADD = 95; // invalid address uint256 internal constant INVALID_ADDRESS = 96; // creator can only renounce in some circumstances uint256 internal constant CREATOR_CANNOT_RENOUNCE = 97; // no price for trade uint256 internal constant NO_PRICE_FOR_TRADE = 98; // Max capital requested uint256 internal constant ZERO_CAPITAL_REQUESTED = 99; // Unwind capital above the limit uint256 internal constant INVALID_CAPITAL_TO_UNWIND = 100; // Mining % sharing does not match uint256 internal constant INVALID_MINING_VALUES = 101; // Max trade slippage percentage uint256 internal constant MAX_TRADE_SLIPPAGE_PERCENTAGE = 102; // Max gas fee percentage uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103; // Mismatch between voters and votes uint256 internal constant INVALID_VOTES_LENGTH = 104; // Only Rewards Distributor uint256 internal constant ONLY_RD = 105; // Fee is too LOW uint256 internal constant FEE_TOO_LOW = 106; // Only governance or emergency uint256 internal constant ONLY_GOVERNANCE_OR_EMERGENCY = 107; // Strategy invalid reserve asset amount uint256 internal constant INVALID_RESERVE_AMOUNT = 108; // Heart only pumps once a week uint256 internal constant HEART_ALREADY_PUMPED = 109; // Heart needs garden votes to pump uint256 internal constant HEART_VOTES_MISSING = 110; // Not enough fees for heart uint256 internal constant HEART_MINIMUM_FEES = 111; // Invalid heart votes length uint256 internal constant HEART_VOTES_LENGTH = 112; // Heart LP tokens not received uint256 internal constant HEART_LP_TOKENS = 113; // Heart invalid asset to lend uint256 internal constant HEART_ASSET_LEND_INVALID = 114; // Heart garden not set uint256 internal constant HEART_GARDEN_NOT_SET = 115; // Heart asset to lend is the same uint256 internal constant HEART_ASSET_LEND_SAME = 116; // Heart invalid ctoken uint256 internal constant HEART_INVALID_CTOKEN = 117; // Price per share is wrong uint256 internal constant PRICE_PER_SHARE_WRONG = 118; // Heart asset to purchase is same uint256 internal constant HEART_ASSET_PURCHASE_INVALID = 119; // Reset hardlock bigger than timestamp uint256 internal constant RESET_HARDLOCK_INVALID = 120; // Invalid referrer uint256 internal constant INVALID_REFERRER = 121; // Only Heart Garden uint256 internal constant ONLY_HEART_GARDEN = 122; // Max BABL Cap to claim by sig uint256 internal constant MAX_BABL_CAP_REACHED = 123; // Not enough BABL uint256 internal constant NOT_ENOUGH_BABL = 124; // Claim garden NFT uint256 internal constant CLAIM_GARDEN_NFT = 125; // Not enough collateral uint256 internal constant NOT_ENOUGH_COLLATERAL = 126; // Amount too low uint256 internal constant AMOUNT_TOO_LOW = 127; // Amount too high uint256 internal constant AMOUNT_TOO_HIGH = 128; // Not enough to repay debt uint256 internal constant SLIPPAGE_TOO_HIH = 129; // Invalid amount uint256 internal constant INVALID_AMOUNT = 130; // Not enough BABL uint256 internal constant NOT_ENOUGH_AMOUNT = 131; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBabController} from '../interfaces/IBabController.sol'; library ControllerLib { /** * Throws if the sender is not the protocol */ function onlyGovernanceOrEmergency(IBabController _controller) internal view { require( msg.sender == _controller.owner() || msg.sender == _controller.EMERGENCY_OWNER(), 'Only governance or emergency can call this' ); } } // 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @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 The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @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); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @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 Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @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; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ICurveMetaRegistry} from './ICurveMetaRegistry.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface ITokenIdentifier { /* ============ Functions ============ */ function identifyTokens( address _tokenIn, address _tokenOut, ICurveMetaRegistry _curveMetaRegistry ) external view returns ( uint8, uint8, address, address ); function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external; function updateVisor(address[] calldata _vaults, bool[] calldata _values) external; function updateSynth(address[] calldata _synths, bool[] calldata _values) external; function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external; function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external; function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ICurveMetaRegistry * @author Babylon Finance * * Interface for interacting with all the curve registries */ interface ICurveMetaRegistry { /* ============ Functions ============ */ function updatePoolsList() external; function updateCryptoRegistries() external; /* ============ View Functions ============ */ function isPool(address _poolAddress) external view returns (bool); function getCoinAddresses(address _pool, bool _getUnderlying) external view returns (address[8] memory); function getNCoins(address _pool) external view returns (uint256); function getLpToken(address _pool) external view returns (address); function getPoolFromLpToken(address _lpToken) external view returns (address); function getVirtualPriceFromLpToken(address _pool) external view returns (uint256); function isMeta(address _pool) external view returns (bool); function getUnderlyingAndRate(address _pool, uint256 _i) external view returns (address, uint256); function findPoolForCoins( address _fromToken, address _toToken, uint256 _i ) external view returns (address); function getCoinIndices( address _pool, address _fromToken, address _toToken ) external view returns ( uint256, uint256, bool ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBaseIntegration} from '../interfaces/IBaseIntegration.sol'; /** * @title ITrade * @author Babylon Finance * * Interface for trading protocol integrations */ interface ITradeIntegration is IBaseIntegration { function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity ) external; function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity, address _hopToken ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IBaseIntegration { function name() external view returns (string memory); } // 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; } }
* @return The result of safely multiplying x and y, interpreting the operands as fixed-point decimals of a standard unit. @dev The operands should be in the standard unit factor which will be divided out after the product of x and y is evaluated, so that product must be less than 2256. Unlike multiplyDecimal, this function rounds the result to the nearest increment. Rounding is useful when you need to retain fidelity for small decimal numbers (eg. small fractions or percentages)./
function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); }
217,814
[ 1, 2463, 1021, 563, 434, 15303, 10194, 310, 619, 471, 677, 16, 10634, 310, 326, 14883, 487, 5499, 17, 1153, 15105, 434, 279, 4529, 2836, 18, 225, 1021, 14883, 1410, 506, 316, 326, 4529, 2836, 5578, 1492, 903, 506, 26057, 596, 1839, 326, 3017, 434, 619, 471, 677, 353, 12697, 16, 1427, 716, 3017, 1297, 506, 5242, 2353, 576, 5034, 18, 25448, 10194, 5749, 16, 333, 445, 21196, 326, 563, 358, 326, 11431, 5504, 18, 11370, 310, 353, 5301, 1347, 1846, 1608, 358, 15096, 13444, 292, 560, 364, 5264, 6970, 5600, 261, 1332, 18, 5264, 8330, 87, 578, 5551, 1023, 2934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 10194, 5749, 11066, 12, 11890, 5034, 619, 16, 2254, 5034, 677, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 7027, 1283, 5749, 11066, 12, 92, 16, 677, 16, 28721, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-07-28 */ pragma solidity 0.6.0; /** * @title Price contract * @dev Price check and call */ contract Nest_3_OfferPrice{ using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestToken; // NestToken Nest_NToken_TokenMapping _tokenMapping; // NToken mapping Nest_3_OfferMain _offerMain; // Offering main contract Nest_3_Abonus _abonus; // Bonus pool address _nTokeOfferMain; // NToken offering main contract address _destructionAddress; // Destruction contract address address _nTokenAuction; // NToken auction contract address struct PriceInfo { // Block price uint256 ethAmount; // ETH amount uint256 erc20Amount; // Erc20 amount uint256 frontBlock; // Last effective block address offerOwner; // Offering address } struct TokenInfo { // Token offer information mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price uint256 latestOffer; // Latest effective block uint256 priceCostLeast; // Minimum ETH cost for prices uint256 priceCostMost; // Maximum ETH cost for prices uint256 priceCostSingle; // ETH cost for single data uint256 priceCostUser; // User ratio of cost } uint256 destructionAmount = 10000 ether; // Amount of NEST to destroy to call prices uint256 effectTime = 1 days; // Waiting time to start calling prices mapping(address => TokenInfo) _tokenInfo; // Token offer information mapping(address => bool) _blocklist; // Block list mapping(address => uint256) _addressEffect; // Effective time of address to call prices mapping(address => bool) _offerMainMapping; // Offering contract mapping // Real-time price token, ETH amount, erc20 amount event NowTokenPrice(address a, uint256 b, uint256 c); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Initialize token price charge parameters * @param tokenAddress Token address */ function addPriceCost(address tokenAddress) public { require(msg.sender == _nTokenAuction); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; tokenInfo.priceCostLeast = 0.001 ether; tokenInfo.priceCostMost = 0.01 ether; tokenInfo.priceCostSingle = 0.0001 ether; tokenInfo.priceCostUser = 2; } /** * @dev Add price * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param endBlock Effective price block * @param tokenAddress Erc20 address * @param offerOwner Offering address */ function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{ // Add effective block price information TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount); //injected INTEGER OVERFLOW OR UNDERFLOW priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW priceInfo.offerOwner = offerOwner; if (endBlock != tokenInfo.latestOffer) { // If different block offer priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; } } /** * @dev Price modification in taker orders * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param tokenAddress Token address * @param endBlock Block of effective price */ function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain { TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount); //injected INTEGER OVERFLOW OR UNDERFLOW priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Update and check the latest price * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount * @return blockNum Price block */ function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(checkUseNestPrice(address(msg.sender))); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; uint256 checkBlock = tokenInfo.latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock; } require(checkBlock != 0); PriceInfo memory priceInfo = tokenInfo.priceInfoList[checkBlock]; address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(tokenInfo.priceCostLeast.sub(tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10)))(address(_nestToken)); } else { _abonus.switchToEth.value(tokenInfo.priceCostLeast.sub(tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10)))(address(nToken)); } repayEth(priceInfo.offerOwner, tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10)); repayEth(address(msg.sender), msg.value.sub(tokenInfo.priceCostLeast)); emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount); return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } /** * @dev Update and check the latest price-internal use * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount */ function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) { TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; uint256 checkBlock = tokenInfo.latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0); } PriceInfo memory priceInfo = tokenInfo.priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount); } /** * @dev Update and check the effective price list * @param tokenAddress Token address * @param num Number of prices to check * @return uint256[] price list */ function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) { require(checkUseNestPrice(address(msg.sender))); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; // Charge uint256 thisPay = tokenInfo.priceCostSingle.mul(num); if (thisPay < tokenInfo.priceCostLeast) { thisPay=tokenInfo.priceCostLeast; } else if (thisPay > tokenInfo.priceCostMost) { thisPay = tokenInfo.priceCostMost; } // Extract data uint256 length = num.mul(3); uint256 index = 0; uint256[] memory data = new uint256[](length); address latestOfferOwner = address(0x0); uint256 checkBlock = tokenInfo.latestOffer; while(index < length && checkBlock > 0){ if (checkBlock < block.number && tokenInfo.priceInfoList[checkBlock].ethAmount != 0) { // Add return data data[index++] = tokenInfo.priceInfoList[checkBlock].ethAmount; data[index++] = tokenInfo.priceInfoList[checkBlock].erc20Amount; data[index++] = checkBlock; if (latestOfferOwner == address(0x0)) { latestOfferOwner = tokenInfo.priceInfoList[checkBlock].offerOwner; } } checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock; } require(latestOfferOwner != address(0x0)); require(length == data.length); // Allocation address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(thisPay.sub(thisPay.mul(tokenInfo.priceCostUser).div(10)))(address(_nestToken)); } else { _abonus.switchToEth.value(thisPay.sub(thisPay.mul(tokenInfo.priceCostUser).div(10)))(address(nToken)); } repayEth(latestOfferOwner, thisPay.mul(tokenInfo.priceCostUser).div(10)); repayEth(address(msg.sender), msg.value.sub(thisPay)); return data; } // Activate the price checking function function activation() public { _nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount); _addressEffect[address(msg.sender)] = now.add(effectTime); } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // Check block price - user account only function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount); } // Check real-time price - user account only function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; uint256 checkBlock = tokenInfo.latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0,0); } PriceInfo storage priceInfo = tokenInfo.priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } // Check the cost allocation ratio function checkPriceCostProportion(address tokenAddress) public view returns(uint256 user, uint256 abonus) { return (_tokenInfo[tokenAddress].priceCostUser, uint256(10).sub(_tokenInfo[tokenAddress].priceCostUser)); } // Check the minimum ETH cost of obtaining the price function checkPriceCostLeast(address tokenAddress) public view returns(uint256) { return _tokenInfo[tokenAddress].priceCostLeast; } // Check the maximum ETH cost of obtaining the price function checkPriceCostMost(address tokenAddress) public view returns(uint256) { return _tokenInfo[tokenAddress].priceCostMost; } // Check the cost of a single price data function checkPriceCostSingle(address tokenAddress) public view returns(uint256) { return _tokenInfo[tokenAddress].priceCostSingle; } // Check whether the price-checking functions can be called function checkUseNestPrice(address target) public view returns (bool) { if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) { return true; } else { return false; } } // Check whether the address is in the blocklist function checkBlocklist(address add) public view returns(bool) { return _blocklist[add]; } // Check the amount of NEST to destroy to call prices function checkDestructionAmount() public view returns(uint256) { return destructionAmount; } // Check the waiting time to start calling prices function checkEffectTime() public view returns (uint256) { return effectTime; } // Modify user ratio of cost function changePriceCostProportion(uint256 user, address tokenAddress) public onlyOwner { _tokenInfo[tokenAddress].priceCostUser = user; } // Modify minimum ETH cost for prices function changePriceCostLeast(uint256 amount, address tokenAddress) public onlyOwner { _tokenInfo[tokenAddress].priceCostLeast = amount; } // Modify maximum ETH cost for prices function changePriceCostMost(uint256 amount, address tokenAddress) public onlyOwner { _tokenInfo[tokenAddress].priceCostMost = amount; } // Modify ETH cost for single data function checkPriceCostSingle(uint256 amount, address tokenAddress) public onlyOwner { _tokenInfo[tokenAddress].priceCostSingle = amount; } // Modify the blocklist function changeBlocklist(address add, bool isBlock) public onlyOwner { _blocklist[add] = isBlock; } // Amount of NEST to destroy to call price-checking functions function changeDestructionAmount(uint256 amount) public onlyOwner { destructionAmount = amount; } // Modify the waiting time to start calling prices function changeEffectTime(uint256 num) public onlyOwner { effectTime = num; } // Offering contract only modifier onlyOfferMain(){ require(_offerMainMapping[address(msg.sender)], "No authority"); _; } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } // Voting contract interface Nest_3_VoteFactory { // Check address function checkAddress(string calldata name) external view returns (address contractAddress); // Check whether administrator function checkOwners(address man) external view returns (bool); } // NToken mapping contract interface Nest_NToken_TokenMapping { function checkTokenMapping(address token) external view returns (address); } // NEST offer main contract interface Nest_3_OfferMain { function checkTokenAllow(address token) external view returns(bool); } // Bonus pool contract interface Nest_3_Abonus { function switchToEth(address token) external payable; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library address_make_payable { function make_payable(address x) internal pure returns (address payable) { return address(uint160(x)); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 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 safeIncreaseAllowance(ERC20 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(ERC20 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)); } function callOptionalReturn(ERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } 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 Add price @param ethAmount ETH amount @param tokenAmount Erc20 amount @param endBlock Effective price block @param tokenAddress Erc20 address @param offerOwner Offering address/ Add effective block price information
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{ TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.offerOwner = offerOwner; if (endBlock != tokenInfo.latestOffer) { priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; } }
12,913,709
[ 1, 986, 6205, 225, 13750, 6275, 512, 2455, 3844, 225, 1147, 6275, 512, 1310, 3462, 3844, 225, 679, 1768, 512, 21446, 6205, 1203, 225, 1147, 1887, 512, 1310, 3462, 1758, 225, 10067, 5541, 25753, 310, 1758, 19, 1436, 11448, 1203, 6205, 1779, 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, 527, 5147, 12, 11890, 5034, 13750, 6275, 16, 2254, 5034, 1147, 6275, 16, 2254, 5034, 679, 1768, 16, 1758, 1147, 1887, 16, 1758, 10067, 5541, 13, 1071, 1338, 10513, 6376, 95, 203, 3639, 3155, 966, 2502, 1147, 966, 273, 389, 2316, 966, 63, 2316, 1887, 15533, 203, 3639, 20137, 966, 2502, 6205, 966, 273, 1147, 966, 18, 8694, 17914, 63, 409, 1768, 15533, 203, 203, 203, 3639, 6205, 966, 18, 23322, 5541, 273, 10067, 5541, 31, 203, 3639, 309, 261, 409, 1768, 480, 1147, 966, 18, 13550, 10513, 13, 288, 203, 5411, 6205, 966, 18, 10211, 1768, 273, 1147, 966, 18, 13550, 10513, 31, 203, 5411, 1147, 966, 18, 13550, 10513, 273, 679, 1768, 31, 203, 3639, 289, 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 ]
pragma solidity ^0.4.11; import './SafeMath.sol'; import './Owned.sol'; /* A library that manages all funds for buyer, seller, and owner roles. */ library AccountLib { /************************************************* * Members *************************************************/ struct Data { // the purchaser of the portfolio who can settle and rebalance at any time address buyer; // the seller who earns fees for putting up collateral address seller; // the smart contract owner who earns fees for infrastructure and market making address owner; // a mapping to keep track of all accountBalances mapping (address => uint) accountBalances; // the time that the prism became Accepted // this serves as the starting time for the pro-rated daily commission uint startTime; // the time that the prism became settled // this serves as the ending time for the pro-rated daily commission uint endTime; // the initial fee to the seller that can be immediately dailysionTransferred after the prism becomes Accepted uint initialCommission; // the amount of ETH that is paid daily to the seller. It can be withdrawn at a pro-rated rate at any time. // NOTE: This is given a fixed amount of ETH here, but is proposed to the Prism as a % of principal. uint dailyCommission; // keep track of how much the seller has dailysionTransferred so prevent repeat withdrawals during the Accepted state uint dailyCommissionTransferred; } /** Sets the buyer, ensuring that funds are transferred internally to the new buyer address. */ function setBuyer(Data storage self, address _buyer) internal { // must use buyerFunds() and sellerFunds() instead of accountBalances directly so that dailyCommission is updated first transfer(self, self.buyer, _buyer, buyerFunds(self)); self.buyer = _buyer; } /** Sets the seller, ensuring that funds are transferred internally to the new seller address. */ function setSeller(Data storage self, address _seller) internal { // must use sellerFunds() instead of accountBalances directly so that dailyCommission is updated first transfer(self, self.seller, _seller, sellerFunds(self)); self.seller = _seller; } /** Sets the owner, ensuring that funds are transferred internally to the new owner address. */ function setOwner(Data storage self, address _owner) internal { // must use sellerFunds() instead of accountBalances directly so that dailyCommission is updated first transfer(self, self.owner, _owner, ownerFunds(self)); self.owner = _owner; } /** Withdraws the given amout of buyer funds to the given address. */ function buyerWithdraw(Data storage self, address to, uint amount) internal { withdrawFrom(self, self.buyer, to, amount); } /** Withdraw available seller funds. If Accepted, withdraws initial commission and a pro-rated amount of daily commission. If Settled, withdraws collateral. */ function sellerWithdraw(Data storage self, address to, uint amount) internal { withdrawFrom(self, self.seller, to, amount); } /** Withdraws all fees to owner account */ function ownerWithdraw(Data storage self, address to, uint amount) internal { withdrawFrom(self, self.owner, to, amount); } /** Withdraws from the balance of an account and sends them to the given address. */ function withdrawFrom(Data storage self, address from, address to, uint amount) internal { if(amount > self.accountBalances[from]) revert(); // funds subtracted first to prevent re-entry self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount); if(!to.call.value(amount)()) revert(); } /** Withdraws the given amout of buyer funds to the given function call.Data storage self, */ function buyerWithdrawCall(Data storage self, address to, uint amount, bytes4 methodId) internal { withdrawCall(self, self.buyer, to, amount, methodId); } /** Withdraws from the balance of an account and sends them with a given function call. */ function withdrawCall(Data storage self, address from, address to, uint amount, bytes4 methodId) internal { if(amount > self.accountBalances[from]) revert(); // funds subtracted first to prevent re-entry self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount); if(!to.call.value(amount)(methodId)) revert(); } /** Withdraw all funds directly. Does not adjust accountBalances. * WARNING: Only to be used as override. */ function withdrawAll(Data storage /*self*/, address to) internal { if(!to.call.value(this.balance)()) revert(); } /** Transfers the given amount from the sender to the specified receiver. */ function transfer(Data storage self, address from, address to, uint amount) internal { if(amount > self.accountBalances[from]) revert(); self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount); self.accountBalances[to] = SafeMath.add(self.accountBalances[to], amount); } /** Transfers all available funds from the sender to the specified receiver. */ function transferAll(Data storage self, address from, address to) internal { self.accountBalances[to] = SafeMath.add(self.accountBalances[to], self.accountBalances[from]); self.accountBalances[from] = 0; // must come after since its used in the calculation above } /** Transfer the daily commission (pro-rated from startTime till now, or endTime if set) from the buyer to the seller. This is called automatically before any call to buyerFunds or sellerFunds to ensure that they use the most up-to-date balances. */ // NOTE: This is safe for anyone to call, since it just transfers any outstanding daily commission to the seller and is idempotent (can be called multiple times without additional effect) function updateDailyCommission(Data storage self) internal { // do not start paying commission until the start time if(self.startTime == 0) return; // get the life of the contract in days (simulated fixed point) // use the current time if endTime is not set (i.e. Settled) uint currentEndTime = self.endTime != 0 ? self.endTime : now; uint lifespanSeconds = currentEndTime - self.startTime; // calculate the amount that the seller can withdraw at this time, based on // the amount of dailyCommission available minus the amount they previously withdrew // NOTE: Do divisions first to avoid overflow uint proratedCommission = SafeMath.subtract(SafeMath.multiply(self.dailyCommission / 1 days, lifespanSeconds), self.dailyCommissionTransferred); // if there are not enough buyer funds, transfer the remaining if (proratedCommission > self.accountBalances[self.buyer]) { proratedCommission = self.accountBalances[self.buyer]; } // keep track of how much the seller withdraws so they can't withdraw it more than once self.dailyCommissionTransferred = SafeMath.add(self.dailyCommissionTransferred, proratedCommission); // finally, transfer the prorated fee from the buyer to the seller // NOTE: Assume that there will always be a prorated commission, so do not bother // saving gas by checking proratedCommission > 0 transfer(self, self.buyer, self.seller, proratedCommission); } function depositTo(Data storage self, address to) internal { self.accountBalances[to] += msg.value; } function depositToBuyer(Data storage self) internal { self.accountBalances[self.buyer] += msg.value; } function depositToSeller(Data storage self) internal { self.accountBalances[self.seller] += msg.value; } /** Accept porfolio proposal */ function acceptProposal(Data storage self, uint _startTime, uint _initialCommission, uint _dailyCommission) internal { self.startTime = _startTime; self.initialCommission = _initialCommission; self.dailyCommission = _dailyCommission; } /** Track when account settles */ function setSettleEndTime(Data storage self, uint _endTime) internal { self.endTime = _endTime; } /** Retrieves the buyer's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */ function buyerFunds(Data storage self) internal returns(uint) { // must transfer pro-rated daily commission from the buyer to the seller to have most up-to-date balance updateDailyCommission(self); return self.accountBalances[self.buyer]; } /** Retrieves the seller's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */ function sellerFunds(Data storage self) internal returns(uint) { // must transfer pro-rated daily commission from the self.buyer to the seller to have most up-to-date balance updateDailyCommission(self); return self.accountBalances[self.seller]; } /** Retrieves the owner's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */ function ownerFunds(Data storage self) internal returns(uint) { // must transfer pro-rated daily commission from the self.buyer to the owner to have most up-to-date balance updateDailyCommission(self); return self.accountBalances[self.owner]; } }
* Withdraw available seller funds. If Accepted, withdraws initial commission and a pro-rated amount of daily commission. If Settled, withdraws collateral. */
function sellerWithdraw(Data storage self, address to, uint amount) internal { withdrawFrom(self, self.seller, to, amount); }
12,891,545
[ 1, 1190, 9446, 2319, 29804, 284, 19156, 18, 971, 8662, 329, 16, 598, 9446, 87, 2172, 1543, 19710, 471, 279, 450, 17, 86, 690, 3844, 434, 18872, 1543, 19710, 18, 971, 1000, 88, 1259, 16, 598, 9446, 87, 4508, 2045, 287, 18, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 29804, 1190, 9446, 12, 751, 2502, 365, 16, 1758, 358, 16, 2254, 3844, 13, 2713, 288, 203, 565, 598, 9446, 1265, 12, 2890, 16, 365, 18, 1786, 749, 16, 358, 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, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-24 */ pragma solidity ^0.6.6; /** * @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; // } } /** * @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 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"); // } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } // function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { // uint256 newAllowance = token.allowance(address(this), spender).add(value); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); // } // function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { // uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); // } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external; } /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ interface ILendingPoolAddressesProvider { function getLendingPoolCore() external view returns (address payable); function getLendingPool() external view returns (address); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal virtual view returns (address payable) { return msg.sender; } // function _msgData() internal view virtual returns (bytes memory) { // this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // return msg.data; // } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ // contract ERC20 is Context, IERC20 { // using SafeMath for uint256; // using Address for address; // mapping (address => uint256) private _balances; // mapping (address => mapping (address => uint256)) private _allowances; // uint256 private _totalSupply; // string private _name; // string private _symbol; // uint8 private _decimals; // /** // * @dev Sets the values for {name} and {symbol}, initializes {decimals} with // * a default value of 18. // * // * To select a different value for {decimals}, use {_setupDecimals}. // * // * All three of these values are immutable: they can only be set once during // * construction. // */ // constructor (string memory name, string memory symbol) public { // _name = name; // _symbol = symbol; // _decimals = 18; // } // /** // * @dev Returns the name of the token. // */ // function name() public view returns (string memory) { // return _name; // } // /** // * @dev Returns the symbol of the token, usually a shorter version of the // * name. // */ // function symbol() public view returns (string memory) { // return _symbol; // } // /** // * @dev Returns the number of decimals used to get its user representation. // * For example, if `decimals` equals `2`, a balance of `505` tokens should // * be displayed to a user as `5,05` (`505 / 10 ** 2`). // * // * Tokens usually opt for a value of 18, imitating the relationship between // * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is // * called. // * // * NOTE: This information is only used for _display_ purposes: it in // * no way affects any of the arithmetic of the contract, including // * {IERC20-balanceOf} and {IERC20-transfer}. // */ // function decimals() public view returns (uint8) { // return _decimals; // } // /** // * @dev See {IERC20-totalSupply}. // */ // function totalSupply() public 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 { } // } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; // event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; // emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ // function renounceOwnership() public virtual onlyOwner { // emit OwnershipTransferred(_owner, address(0)); // _owner = address(0); // } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ // function transferOwnership(address newOwner) public virtual onlyOwner { // require(newOwner != address(0), "Ownable: new owner is the zero address"); // emit OwnershipTransferred(_owner, newOwner); // _owner = newOwner; // } } /** Ensures that any contract that inherits from this contract is able to withdraw funds that are accidentally received or stuck. */ contract Withdrawable is Ownable { using SafeERC20 for IERC20; address constant ETHER = address(0); // event LogWithdraw( // address indexed _from, // address indexed _assetAddress, // uint amount // ); /** * @dev Withdraw asset. * @param _assetAddress Asset to be withdrawn. */ function withdraw(address _assetAddress) public onlyOwner { uint256 assetBalance; if (_assetAddress == ETHER) { address self = address(this); // workaround for a possible solidity bug assetBalance = self.balance; msg.sender.transfer(assetBalance); } else { assetBalance = IERC20(_assetAddress).balanceOf(address(this)); IERC20(_assetAddress).safeTransfer(msg.sender, assetBalance); } // emit LogWithdraw(msg.sender, _assetAddress, assetBalance); } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver, Withdrawable { using SafeERC20 for IERC20; using SafeMath for uint256; address constant ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPoolAddressesProvider public addressesProvider; constructor(address _addressProvider) public { addressesProvider = ILendingPoolAddressesProvider(_addressProvider); } receive() external payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core, _reserve, _amount); } function transferInternal( address payable _destination, address _reserve, uint256 _amount ) internal { if (_reserve == ethAddress) { (bool success, ) = _destination.call{value: _amount}(""); require(success == true, "Couldn't transfer ETH"); return; } IERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns (uint256) { if (_reserve == ethAddress) { return _target.balance; } return IERC20(_reserve).balanceOf(_target); } } interface ILendingPool { function addressesProvider() external view returns (address); // function deposit ( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; // function redeemUnderlying ( address _reserve, address _user, uint256 _amount ) external; // function borrow ( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external; // function repay ( address _reserve, uint256 _amount, address _onBehalfOf ) external payable; // function swapBorrowRateMode ( address _reserve ) external; // function rebalanceFixedBorrowRate ( address _reserve, address _user ) external; // function setUserUseReserveAsCollateral ( address _reserve, bool _useAsCollateral ) external; // function liquidationCall ( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable; function flashLoan( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external; // function getReserveConfigurationData ( address _reserve ) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive ); // function getReserveData ( address _reserve ) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ); // function getUserAccountData ( address _user ) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); // function getUserReserveData ( address _reserve, address _user ) external view returns ( uint256 currentATokenBalance, uint256 currentUnderlyingBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ); // function getReserves () external view; } interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } interface IBank { function withdraw(address underlying, uint256 withdrawTokens) external; function controller() external view returns (address); function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) external payable; } interface IFToken { function balanceOf(address account) external view returns (uint256); } interface IBankController { function getFTokeAddress(address underlying) external view returns (address); } contract FlashloanForTube is FlashLoanReceiverBase { using SafeERC20 for IERC20; address public bank = address(0xdE7B3b2Fe0E7b4925107615A5b199a4EB40D9ca9); address[] public reserve2BorrowRouting; address[] public swap2TokenRouting; address public uniRouterV2 = address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for for <> weth <> usdc route constructor(address _addressProvider) public FlashLoanReceiverBase(_addressProvider) {} function doApprove(address erc20, address spender) public { IERC20(erc20).safeApprove(spender, 0); IERC20(erc20).safeApprove(spender, uint256(-1)); } /** This function is called after your contract has received the flash loaned amount */ function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { require( _amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?" ); // // Your logic goes here. // !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !! // ( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) = abi.decode(_params, (address, address, address, uint256)); if (_reserve != underlyingBorrow) { // reserve2BorrowRouting = [_reserve, weth, underlyingBorrow]; IUniswapRouter(uniRouterV2).swapExactTokensForTokens( IERC20(_reserve).balanceOf(address(this)), 0, reserve2BorrowRouting, address(this), now.add(1800) ); } doApprove(_reserve, bank); IBank(bank).liquidateBorrow( borrower, underlyingBorrow, underlyingCollateral, repayAmount ); IBankController ctrl = IBankController(IBank(bank).controller()); IFToken fToken = IFToken(ctrl.getFTokeAddress(underlyingCollateral)); IBank(bank).withdraw( underlyingCollateral, fToken.balanceOf(address(this)) ); //use uniswap doApprove(underlyingCollateral, uniRouterV2); // swap2TokenRouting = [underlyingCollateral, weth, _reserve]; IUniswapRouter(uniRouterV2).swapExactTokensForTokens( IERC20(underlyingCollateral).balanceOf(address(this)), 0, swap2TokenRouting, address(this), now.add(1800) ); uint256 totalDebt = _amount.add(_fee); transferFundsBackToPoolInternal(_reserve, totalDebt); } /** Flash loan _amount worth of `_asset` with _data */ function flashloan( address _asset, uint256 _amount, bytes calldata _data ) external onlyOwner { ILendingPool lendingPool = ILendingPool( addressesProvider.getLendingPool() ); lendingPool.flashLoan(address(this), _asset, _amount, _data); } function set( address _bank, address _weth, address _uniRouterV2, address _addressesProvider ) external onlyOwner { bank = _bank; weth = _weth; uniRouterV2 = _uniRouterV2; addressesProvider = ILendingPoolAddressesProvider(_addressesProvider); } function setRouting( address[] calldata _reserve2BorrowRouting, address[] calldata _swap2TokenRouting ) external onlyOwner { reserve2BorrowRouting = _reserve2BorrowRouting; swap2TokenRouting = _swap2TokenRouting; } }
* @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 { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } }
8,061,757
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 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 ]
./full_match/1/0xadeC97DDc587F5285528069112b9B09F5aE5D15e/sources/CyberSamurai.sol
* the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Mask of an entry in packed address data. The bit position of `numberMinted` in packed address data. The bit position of `numberBurned` in packed address data. The bit position of `aux` in packed address data. Mask of all 256 bits in packed address data except the 64 bits for `aux`. The bit position of `startTimestamp` in packed ownership. The bit mask of the `burned` bit in packed ownership. The bit position of the `nextInitialized` bit in packed ownership. The bit mask of the `nextInitialized` bit in packed ownership. The tokenId of the next token to be minted. The number of tokens burned. Token name Token symbol Mapping from token ID to ownership details An empty struct value does not necessarily mean the token is unowned. See `_packedOwnershipOf` implementation for details. Bits Layout: - [0..159] `addr` - [160..223] `startTimestamp` - [224] `burned` - [225] `nextInitialized` Mapping owner address to address data. Bits Layout: - [0..63] `balance` - [64..127] `numberMinted` - [128..191] `numberBurned` - [192..255] `aux` Mapping from token ID to approved address. Mapping from owner to operator approvals
contract ERC721A is IERC721A { uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; uint256 private constant BITPOS_NUMBER_MINTED = 64; uint256 private constant BITPOS_NUMBER_BURNED = 128; uint256 private constant BITPOS_AUX = 192; uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; uint256 private constant BITPOS_START_TIMESTAMP = 160; uint256 private constant BITMASK_BURNED = 1 << 224; uint256 private constant BITPOS_NEXT_INITIALIZED = 225; uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225; uint256 private _currentIndex; uint256 private _burnCounter; string private _name; string private _symbol; mapping(uint256 => uint256) private _packedOwnerships; mapping(address => uint256) private _packedAddressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function _nextTokenId() internal view returns (uint256) { return _currentIndex; } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalBurned() internal view returns (uint256) { return _burnCounter; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x5b5e139f; } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY; } function _numberMinted(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY; } function _numberBurned(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY; } function _getAux(address owner) internal view returns (uint64) { return uint64(_packedAddressData[owner] >> BITPOS_AUX); } function _setAux(address owner, uint64 aux) internal { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; auxCasted := aux } packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX); _packedAddressData[owner] = packed; }
8,365,190
[ 1, 5787, 6912, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 389, 1937, 1345, 548, 1435, 261, 7606, 358, 374, 16, 425, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 25374, 716, 326, 4207, 1147, 612, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 16698, 434, 392, 1241, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 2696, 49, 474, 329, 68, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 2696, 38, 321, 329, 68, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 18196, 68, 316, 12456, 1758, 501, 18, 16698, 434, 777, 8303, 4125, 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, 4232, 39, 27, 5340, 37, 353, 467, 654, 39, 27, 5340, 37, 288, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 15140, 67, 4883, 67, 19083, 273, 261, 21, 2296, 5178, 13, 300, 404, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 9931, 67, 6236, 6404, 273, 5178, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 9931, 67, 38, 8521, 2056, 273, 8038, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 14237, 60, 273, 20217, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 14237, 60, 67, 10057, 7618, 273, 261, 21, 2296, 20217, 13, 300, 404, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 7570, 67, 17201, 273, 25430, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 38, 8521, 2056, 273, 404, 2296, 576, 3247, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 25539, 67, 12919, 25991, 273, 28298, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 25539, 67, 12919, 25991, 273, 404, 2296, 28298, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 1016, 31, 203, 203, 565, 2254, 5034, 3238, 389, 70, 321, 4789, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 2920, 329, 5460, 12565, 87, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 2920, 329, 1887, 751, 2 ]
./partial_match/1/0x1d2Cbe37E22E01DB3c513db44DE8458EA598A861/sources/script/Curvy.flat.sol
@solidity memory-safe-assembly Get a pointer to some free memory. Write the abi-encoded calldata into memory, beginning with the function selector. Set success to whether the call reverted, if not we check it either returned exactly 1 (can't just be non-zero data), or had no return data. We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. Counterintuitively, this call must be positioned second to the or() call in the surrounding and() call or else returndatasize() will be zero during the computation.
function safeApprove(ERC20 token, address to, uint256 amount) internal { bool success; assembly { let freeMemoryPointer := mload(0x40) mstore( freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000 ) mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) success := and( or( and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize()) ), call(gas(), token, 0, freeMemoryPointer, 68, 0, 32) ) } require(success, "APPROVE_FAILED"); }
3,600,673
[ 1, 36, 30205, 560, 3778, 17, 4626, 17, 28050, 968, 279, 4407, 358, 2690, 4843, 3778, 18, 2598, 326, 24126, 17, 10787, 745, 892, 1368, 3778, 16, 8435, 598, 326, 445, 3451, 18, 1000, 2216, 358, 2856, 326, 745, 15226, 329, 16, 309, 486, 732, 866, 518, 3344, 2106, 8950, 404, 261, 4169, 1404, 2537, 506, 1661, 17, 7124, 501, 3631, 578, 9323, 1158, 327, 501, 18, 1660, 999, 23797, 2724, 326, 769, 434, 3134, 745, 892, 19489, 731, 3007, 1427, 30, 1059, 397, 3847, 225, 576, 18, 1660, 999, 374, 471, 3847, 358, 1610, 731, 358, 3847, 1731, 434, 327, 501, 1368, 326, 15289, 3476, 18, 9354, 474, 14945, 4492, 16, 333, 745, 1297, 506, 1754, 329, 2205, 358, 326, 578, 1435, 745, 316, 326, 29071, 471, 1435, 745, 578, 469, 327, 13178, 554, 1435, 903, 506, 3634, 4982, 326, 16039, 18, 2, 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, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 12053, 537, 12, 654, 39, 3462, 1147, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 1426, 2216, 31, 203, 203, 3639, 19931, 288, 203, 5411, 2231, 4843, 6031, 4926, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 203, 5411, 312, 2233, 12, 203, 7734, 4843, 6031, 4926, 16, 203, 7734, 374, 92, 5908, 25, 24852, 27, 70, 23, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 203, 5411, 262, 203, 5411, 312, 2233, 12, 203, 7734, 527, 12, 9156, 6031, 4926, 16, 1059, 3631, 203, 7734, 471, 12, 869, 16, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 13, 203, 203, 5411, 2216, 519, 203, 7734, 471, 12, 203, 10792, 578, 12, 203, 13491, 471, 12, 11253, 12, 81, 945, 12, 20, 3631, 404, 3631, 9879, 12, 2463, 13178, 554, 9334, 8231, 13, 3631, 203, 13491, 353, 7124, 12, 2463, 13178, 554, 10756, 203, 10792, 262, 16, 203, 10792, 745, 12, 31604, 9334, 1147, 16, 374, 16, 4843, 6031, 4926, 16, 23797, 16, 374, 16, 3847, 13, 203, 7734, 262, 203, 3639, 289, 203, 203, 3639, 2583, 12, 4768, 16, 315, 2203, 3373, 3412, 67, 11965, 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 ]
./full_match/5/0x21517abae577dDC59Ac6945C501F36AF085d97A7/sources/contracts/CrowdFunding.sol
array of donations from the above donators there multiple amounts in the array
uint256[] donations;
1,856,055
[ 1, 1126, 434, 2727, 1012, 628, 326, 5721, 2727, 3062, 1915, 3229, 30980, 316, 326, 526, 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, 2254, 5034, 8526, 2727, 1012, 31, 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 ]
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "./interfaces/IGovernance.sol"; import "./Proposals.sol"; import "../common/interfaces/IAccounts.sol"; import "../common/ExtractFunctionSignature.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/IntegerSortedLinkedList.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title A contract for making, passing, and executing on-chain governance proposals. */ contract Governance is IGovernance, ICeloVersionedContract, Ownable, Initializable, ReentrancyGuard, UsingRegistry, UsingPrecompiles { using Proposals for Proposals.Proposal; using FixidityLib for FixidityLib.Fraction; using SafeMath for uint256; using IntegerSortedLinkedList for SortedLinkedList.List; using BytesLib for bytes; using Address for address payable; // prettier-ignore uint256 private constant FIXED_HALF = 500000000000000000000000; enum VoteValue { None, Abstain, No, Yes } struct UpvoteRecord { uint256 proposalId; uint256 weight; } struct VoteRecord { Proposals.VoteValue value; uint256 proposalId; uint256 weight; } struct Voter { // Key of the proposal voted for in the proposal queue UpvoteRecord upvote; uint256 mostRecentReferendumProposal; // Maps a `dequeued` index to a voter's vote record. mapping(uint256 => VoteRecord) referendumVotes; } struct ContractConstitution { FixidityLib.Fraction defaultThreshold; // Maps a function ID to a corresponding threshold, overriding the default. mapping(bytes4 => FixidityLib.Fraction) functionThresholds; } struct HotfixRecord { bool executed; bool approved; uint256 preparedEpoch; mapping(address => bool) whitelisted; } // The baseline is updated as // max{floor, (1 - baselineUpdateFactor) * baseline + baselineUpdateFactor * participation} struct ParticipationParameters { // The average network participation in governance, weighted toward recent proposals. FixidityLib.Fraction baseline; // The lower bound on the participation baseline. FixidityLib.Fraction baselineFloor; // The weight of the most recent proposal's participation on the baseline. FixidityLib.Fraction baselineUpdateFactor; // The proportion of the baseline that constitutes quorum. FixidityLib.Fraction baselineQuorumFactor; } Proposals.StageDurations public stageDurations; uint256 public queueExpiry; uint256 public dequeueFrequency; address public approver; uint256 public lastDequeue; uint256 public concurrentProposals; uint256 public proposalCount; uint256 public minDeposit; mapping(address => uint256) public refundedDeposits; mapping(address => ContractConstitution) private constitution; mapping(uint256 => Proposals.Proposal) private proposals; mapping(address => Voter) private voters; mapping(bytes32 => HotfixRecord) public hotfixes; SortedLinkedList.List private queue; uint256[] public dequeued; uint256[] public emptyIndices; ParticipationParameters private participationParameters; event ApproverSet(address indexed approver); event ConcurrentProposalsSet(uint256 concurrentProposals); event MinDepositSet(uint256 minDeposit); event QueueExpirySet(uint256 queueExpiry); event DequeueFrequencySet(uint256 dequeueFrequency); event ApprovalStageDurationSet(uint256 approvalStageDuration); event ReferendumStageDurationSet(uint256 referendumStageDuration); event ExecutionStageDurationSet(uint256 executionStageDuration); event ConstitutionSet(address indexed destination, bytes4 indexed functionId, uint256 threshold); event ProposalQueued( uint256 indexed proposalId, address indexed proposer, uint256 transactionCount, uint256 deposit, uint256 timestamp ); event ProposalUpvoted(uint256 indexed proposalId, address indexed account, uint256 upvotes); event ProposalUpvoteRevoked( uint256 indexed proposalId, address indexed account, uint256 revokedUpvotes ); event ProposalDequeued(uint256 indexed proposalId, uint256 timestamp); event ProposalApproved(uint256 indexed proposalId); event ProposalVoted( uint256 indexed proposalId, address indexed account, uint256 value, uint256 weight ); event ProposalExecuted(uint256 indexed proposalId); event ProposalExpired(uint256 indexed proposalId); event ParticipationBaselineUpdated(uint256 participationBaseline); event ParticipationFloorSet(uint256 participationFloor); event ParticipationBaselineUpdateFactorSet(uint256 baselineUpdateFactor); event ParticipationBaselineQuorumFactorSet(uint256 baselineQuorumFactor); event HotfixWhitelisted(bytes32 indexed hash, address whitelister); event HotfixApproved(bytes32 indexed hash); event HotfixPrepared(bytes32 indexed hash, uint256 indexed epoch); event HotfixExecuted(bytes32 indexed hash); modifier hotfixNotExecuted(bytes32 hash) { require(!hotfixes[hash].executed, "hotfix already executed"); _; } modifier onlyApprover() { require(msg.sender == approver, "msg.sender not approver"); _; } function() external payable { require(msg.data.length == 0, "unknown method"); } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 2); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry contract. * @param _approver The address that needs to approve proposals to move to the referendum stage. * @param _concurrentProposals The number of proposals to dequeue at once. * @param _minDeposit The minimum CELO deposit needed to make a proposal. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. * @param approvalStageDuration The number of seconds the approver has to approve a proposal * after it is dequeued. * @param referendumStageDuration The number of seconds users have to vote on a dequeued proposal * after the approval stage ends. * @param executionStageDuration The number of seconds users have to execute a passed proposal * after the referendum stage ends. * @param participationBaseline The initial value of the participation baseline. * @param participationFloor The participation floor. * @param baselineUpdateFactor The weight of the new participation in the baseline update rule. * @param baselineQuorumFactor The proportion of the baseline that constitutes quorum. * @dev Should be called only once. */ function initialize( address registryAddress, address _approver, uint256 _concurrentProposals, uint256 _minDeposit, uint256 _queueExpiry, uint256 _dequeueFrequency, uint256 approvalStageDuration, uint256 referendumStageDuration, uint256 executionStageDuration, uint256 participationBaseline, uint256 participationFloor, uint256 baselineUpdateFactor, uint256 baselineQuorumFactor ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setApprover(_approver); setConcurrentProposals(_concurrentProposals); setMinDeposit(_minDeposit); setQueueExpiry(_queueExpiry); setDequeueFrequency(_dequeueFrequency); setApprovalStageDuration(approvalStageDuration); setReferendumStageDuration(referendumStageDuration); setExecutionStageDuration(executionStageDuration); setParticipationBaseline(participationBaseline); setParticipationFloor(participationFloor); setBaselineUpdateFactor(baselineUpdateFactor); setBaselineQuorumFactor(baselineQuorumFactor); // solhint-disable-next-line not-rely-on-time lastDequeue = now; } /** * @notice Updates the address that has permission to approve proposals in the approval stage. * @param _approver The address that has permission to approve proposals in the approval stage. */ function setApprover(address _approver) public onlyOwner { require(_approver != address(0), "Approver cannot be 0"); require(_approver != approver, "Approver unchanged"); approver = _approver; emit ApproverSet(_approver); } /** * @notice Updates the number of proposals to dequeue at a time. * @param _concurrentProposals The number of proposals to dequeue at at a time. */ function setConcurrentProposals(uint256 _concurrentProposals) public onlyOwner { require(_concurrentProposals > 0, "Number of proposals must be larger than zero"); require(_concurrentProposals != concurrentProposals, "Number of proposals unchanged"); concurrentProposals = _concurrentProposals; emit ConcurrentProposalsSet(_concurrentProposals); } /** * @notice Updates the minimum deposit needed to make a proposal. * @param _minDeposit The minimum CELO deposit needed to make a proposal. */ function setMinDeposit(uint256 _minDeposit) public onlyOwner { require(_minDeposit > 0, "minDeposit must be larger than 0"); require(_minDeposit != minDeposit, "Minimum deposit unchanged"); minDeposit = _minDeposit; emit MinDepositSet(_minDeposit); } /** * @notice Updates the number of seconds before a queued proposal expires. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. */ function setQueueExpiry(uint256 _queueExpiry) public onlyOwner { require(_queueExpiry > 0, "QueueExpiry must be larger than 0"); require(_queueExpiry != queueExpiry, "QueueExpiry unchanged"); queueExpiry = _queueExpiry; emit QueueExpirySet(_queueExpiry); } /** * @notice Updates the minimum number of seconds before the next batch of proposals can be * dequeued. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. */ function setDequeueFrequency(uint256 _dequeueFrequency) public onlyOwner { require(_dequeueFrequency > 0, "dequeueFrequency must be larger than 0"); require(_dequeueFrequency != dequeueFrequency, "dequeueFrequency unchanged"); dequeueFrequency = _dequeueFrequency; emit DequeueFrequencySet(_dequeueFrequency); } /** * @notice Updates the number of seconds proposals stay in the approval stage. * @param approvalStageDuration The number of seconds proposals stay in the approval stage. */ function setApprovalStageDuration(uint256 approvalStageDuration) public onlyOwner { require(approvalStageDuration > 0, "Duration must be larger than 0"); require(approvalStageDuration != stageDurations.approval, "Duration unchanged"); stageDurations.approval = approvalStageDuration; emit ApprovalStageDurationSet(approvalStageDuration); } /** * @notice Updates the number of seconds proposals stay in the referendum stage. * @param referendumStageDuration The number of seconds proposals stay in the referendum stage. */ function setReferendumStageDuration(uint256 referendumStageDuration) public onlyOwner { require(referendumStageDuration > 0, "Duration must be larger than 0"); require(referendumStageDuration != stageDurations.referendum, "Duration unchanged"); stageDurations.referendum = referendumStageDuration; emit ReferendumStageDurationSet(referendumStageDuration); } /** * @notice Updates the number of seconds proposals stay in the execution stage. * @param executionStageDuration The number of seconds proposals stay in the execution stage. */ function setExecutionStageDuration(uint256 executionStageDuration) public onlyOwner { require(executionStageDuration > 0, "Duration must be larger than 0"); require(executionStageDuration != stageDurations.execution, "Duration unchanged"); stageDurations.execution = executionStageDuration; emit ExecutionStageDurationSet(executionStageDuration); } /** * @notice Updates the participation baseline. * @param participationBaseline The value of the baseline. */ function setParticipationBaseline(uint256 participationBaseline) public onlyOwner { FixidityLib.Fraction memory participationBaselineFrac = FixidityLib.wrap(participationBaseline); require( FixidityLib.isProperFraction(participationBaselineFrac), "Participation baseline greater than one" ); require( !participationBaselineFrac.equals(participationParameters.baseline), "Participation baseline unchanged" ); participationParameters.baseline = participationBaselineFrac; emit ParticipationBaselineUpdated(participationBaseline); } /** * @notice Updates the floor of the participation baseline. * @param participationFloor The value at which the baseline is floored. */ function setParticipationFloor(uint256 participationFloor) public onlyOwner { FixidityLib.Fraction memory participationFloorFrac = FixidityLib.wrap(participationFloor); require( FixidityLib.isProperFraction(participationFloorFrac), "Participation floor greater than one" ); require( !participationFloorFrac.equals(participationParameters.baselineFloor), "Participation baseline floor unchanged" ); participationParameters.baselineFloor = participationFloorFrac; emit ParticipationFloorSet(participationFloor); } /** * @notice Updates the weight of the new participation in the baseline update rule. * @param baselineUpdateFactor The new baseline update factor. */ function setBaselineUpdateFactor(uint256 baselineUpdateFactor) public onlyOwner { FixidityLib.Fraction memory baselineUpdateFactorFrac = FixidityLib.wrap(baselineUpdateFactor); require( FixidityLib.isProperFraction(baselineUpdateFactorFrac), "Baseline update factor greater than one" ); require( !baselineUpdateFactorFrac.equals(participationParameters.baselineUpdateFactor), "Baseline update factor unchanged" ); participationParameters.baselineUpdateFactor = baselineUpdateFactorFrac; emit ParticipationBaselineUpdateFactorSet(baselineUpdateFactor); } /** * @notice Updates the proportion of the baseline that constitutes quorum. * @param baselineQuorumFactor The new baseline quorum factor. */ function setBaselineQuorumFactor(uint256 baselineQuorumFactor) public onlyOwner { FixidityLib.Fraction memory baselineQuorumFactorFrac = FixidityLib.wrap(baselineQuorumFactor); require( FixidityLib.isProperFraction(baselineQuorumFactorFrac), "Baseline quorum factor greater than one" ); require( !baselineQuorumFactorFrac.equals(participationParameters.baselineQuorumFactor), "Baseline quorum factor unchanged" ); participationParameters.baselineQuorumFactor = baselineQuorumFactorFrac; emit ParticipationBaselineQuorumFactorSet(baselineQuorumFactor); } /** * @notice Updates the ratio of yes:yes+no votes needed for a specific class of proposals to pass. * @param destination The destination of proposals for which this threshold should apply. * @param functionId The function ID of proposals for which this threshold should apply. Zero * will set the default. * @param threshold The threshold. * @dev If no constitution is explicitly set the default is a simple majority, i.e. 1:2. */ function setConstitution(address destination, bytes4 functionId, uint256 threshold) external onlyOwner { require(destination != address(0), "Destination cannot be zero"); require( threshold > FIXED_HALF && threshold <= FixidityLib.fixed1().unwrap(), "Threshold has to be greater than majority and not greater than unanimity" ); if (functionId == 0) { constitution[destination].defaultThreshold = FixidityLib.wrap(threshold); } else { constitution[destination].functionThresholds[functionId] = FixidityLib.wrap(threshold); } emit ConstitutionSet(destination, functionId, threshold); } /** * @notice Creates a new proposal and adds it to end of the queue with no upvotes. * @param values The values of CELO to be sent in the proposed transactions. * @param destinations The destination addresses of the proposed transactions. * @param data The concatenated data to be included in the proposed transactions. * @param dataLengths The lengths of each transaction's data. * @return The ID of the newly proposed proposal. * @dev The minimum deposit must be included with the proposal, returned if/when the proposal is * dequeued. */ function propose( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths, string calldata descriptionUrl ) external payable returns (uint256) { dequeueProposalsIfReady(); require(msg.value >= minDeposit, "Too small deposit"); proposalCount = proposalCount.add(1); Proposals.Proposal storage proposal = proposals[proposalCount]; proposal.make(values, destinations, data, dataLengths, msg.sender, msg.value); proposal.setDescriptionUrl(descriptionUrl); queue.push(proposalCount); // solhint-disable-next-line not-rely-on-time emit ProposalQueued(proposalCount, msg.sender, proposal.transactions.length, msg.value, now); return proposalCount; } /** * @notice Removes a proposal if it is queued and expired. * @param proposalId The ID of the proposal to remove. * @return Whether the proposal was removed. */ function removeIfQueuedAndExpired(uint256 proposalId) private returns (bool) { if (isQueued(proposalId) && isQueuedProposalExpired(proposalId)) { queue.remove(proposalId); emit ProposalExpired(proposalId); return true; } return false; } /** * @notice Requires a proposal is dequeued and removes it if expired. * @param proposalId The ID of the proposal. * @return The proposal storage struct and stage corresponding to `proposalId`. */ function requireDequeuedAndDeleteExpired(uint256 proposalId, uint256 index) private returns (Proposals.Proposal storage, Proposals.Stage) { Proposals.Proposal storage proposal = proposals[proposalId]; require(_isDequeuedProposal(proposal, proposalId, index), "Proposal not dequeued"); Proposals.Stage stage = proposal.getDequeuedStage(stageDurations); if (_isDequeuedProposalExpired(proposal, stage)) { deleteDequeuedProposal(proposal, proposalId, index); } return (proposal, stage); } /** * @notice Upvotes a queued proposal. * @param proposalId The ID of the proposal to upvote. * @param lesser The ID of the proposal that will be just behind `proposalId` in the queue. * @param greater The ID of the proposal that will be just ahead `proposalId` in the queue. * @return Whether or not the upvote was made successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. * @dev Reverts if the account has already upvoted a proposal in the queue. */ function upvote(uint256 proposalId, uint256 lesser, uint256 greater) external nonReentrant returns (bool) { dequeueProposalsIfReady(); // If acting on an expired proposal, expire the proposal and take no action. if (removeIfQueuedAndExpired(proposalId)) { return false; } address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; removeIfQueuedAndExpired(voter.upvote.proposalId); // We can upvote a proposal in the queue if we're not already upvoting a proposal in the queue. uint256 weight = getLockedGold().getAccountTotalLockedGold(account); require(weight > 0, "cannot upvote without locking gold"); require(queue.contains(proposalId), "cannot upvote a proposal not in the queue"); require( voter.upvote.proposalId == 0 || !queue.contains(voter.upvote.proposalId), "cannot upvote more than one queued proposal" ); uint256 upvotes = queue.getValue(proposalId).add(weight); queue.update(proposalId, upvotes, lesser, greater); voter.upvote = UpvoteRecord(proposalId, weight); emit ProposalUpvoted(proposalId, account, weight); return true; } /** * @notice Returns stage of governance process given proposal is in * @param proposalId The ID of the proposal to query. * @return proposal stage */ function getProposalStage(uint256 proposalId) external view returns (Proposals.Stage) { if (proposalId == 0 || proposalId > proposalCount) { return Proposals.Stage.None; } else if (isQueued(proposalId)) { return isQueuedProposalExpired(proposalId) ? Proposals.Stage.Expiration : Proposals.Stage.Queued; } else { return proposals[proposalId].getDequeuedStage(stageDurations); } } /** * @notice Revokes an upvote on a queued proposal. * @param lesser The ID of the proposal that will be just behind the previously upvoted proposal * in the queue. * @param greater The ID of the proposal that will be just ahead of the previously upvoted * proposal in the queue. * @return Whether or not the upvote was revoked successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. */ function revokeUpvote(uint256 lesser, uint256 greater) external nonReentrant returns (bool) { dequeueProposalsIfReady(); address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; uint256 proposalId = voter.upvote.proposalId; require(proposalId != 0, "Account has no historical upvote"); removeIfQueuedAndExpired(proposalId); if (queue.contains(proposalId)) { queue.update( proposalId, queue.getValue(proposalId).sub(voter.upvote.weight), lesser, greater ); emit ProposalUpvoteRevoked(proposalId, account, voter.upvote.weight); } voter.upvote = UpvoteRecord(0, 0); return true; } /** * @notice Approves a proposal in the approval stage. * @param proposalId The ID of the proposal to approve. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the approval was made successfully. */ function approve(uint256 proposalId, uint256 index) external onlyApprover returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); if (!proposal.exists()) { return false; } require(!proposal.isApproved(), "Proposal already approved"); require(stage == Proposals.Stage.Approval, "Proposal not in approval stage"); proposal.approved = true; // Ensures networkWeight is set by the end of the Referendum stage, even if 0 votes are cast. proposal.networkWeight = getLockedGold().getTotalLockedGold(); emit ProposalApproved(proposalId); return true; } /** * @notice Votes on a proposal in the referendum stage. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @param value Whether to vote yes, no, or abstain. * @return Whether or not the vote was cast successfully. */ /* solhint-disable code-complexity */ function vote(uint256 proposalId, uint256 index, Proposals.VoteValue value) external nonReentrant returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); if (!proposal.exists()) { return false; } address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; uint256 weight = getLockedGold().getAccountTotalLockedGold(account); require(proposal.isApproved(), "Proposal not approved"); require(stage == Proposals.Stage.Referendum, "Incorrect proposal state"); require(value != Proposals.VoteValue.None, "Vote value unset"); require(weight > 0, "Voter weight zero"); VoteRecord storage voteRecord = voter.referendumVotes[index]; proposal.updateVote( voteRecord.weight, weight, (voteRecord.proposalId == proposalId) ? voteRecord.value : Proposals.VoteValue.None, value ); proposal.networkWeight = getLockedGold().getTotalLockedGold(); voter.referendumVotes[index] = VoteRecord(value, proposalId, weight); if (proposal.timestamp > proposals[voter.mostRecentReferendumProposal].timestamp) { voter.mostRecentReferendumProposal = proposalId; } emit ProposalVoted(proposalId, account, uint256(value), weight); return true; } /* solhint-enable code-complexity */ /** * @notice Executes a proposal in the execution stage, removing it from `dequeued`. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the proposal was executed successfully. * @dev Does not remove the proposal if the execution fails. */ function execute(uint256 proposalId, uint256 index) external nonReentrant returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); bool notExpired = proposal.exists(); if (notExpired) { require( stage == Proposals.Stage.Execution && _isProposalPassing(proposal), "Proposal not in execution stage or not passing" ); proposal.execute(); emit ProposalExecuted(proposalId); deleteDequeuedProposal(proposal, proposalId, index); } return notExpired; } /** * @notice Approves the hash of a hotfix transaction(s). * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be approved. */ function approveHotfix(bytes32 hash) external hotfixNotExecuted(hash) onlyApprover { hotfixes[hash].approved = true; emit HotfixApproved(hash); } /** * @notice Returns whether given hotfix hash has been whitelisted by given address. * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be whitelisted. * @param whitelister Address to check whitelist status of. */ function isHotfixWhitelistedBy(bytes32 hash, address whitelister) public view returns (bool) { return hotfixes[hash].whitelisted[whitelister]; } /** * @notice Whitelists the hash of a hotfix transaction(s). * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be whitelisted. */ function whitelistHotfix(bytes32 hash) external hotfixNotExecuted(hash) { hotfixes[hash].whitelisted[msg.sender] = true; emit HotfixWhitelisted(hash, msg.sender); } /** * @notice Gives hotfix a prepared epoch for execution. * @param hash The hash of the hotfix to be prepared. */ function prepareHotfix(bytes32 hash) external hotfixNotExecuted(hash) { require(isHotfixPassing(hash), "hotfix not whitelisted by 2f+1 validators"); uint256 epoch = getEpochNumber(); require(hotfixes[hash].preparedEpoch < epoch, "hotfix already prepared for this epoch"); hotfixes[hash].preparedEpoch = epoch; emit HotfixPrepared(hash, epoch); } /** * @notice Executes a whitelisted proposal. * @param values The values of CELO to be sent in the proposed transactions. * @param destinations The destination addresses of the proposed transactions. * @param data The concatenated data to be included in the proposed transactions. * @param dataLengths The lengths of each transaction's data. * @param salt Arbitrary salt associated with hotfix which guarantees uniqueness of hash. * @dev Reverts if hotfix is already executed, not approved, or not prepared for current epoch. */ function executeHotfix( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths, bytes32 salt ) external { bytes32 hash = keccak256(abi.encode(values, destinations, data, dataLengths, salt)); (bool approved, bool executed, uint256 preparedEpoch) = getHotfixRecord(hash); require(!executed, "hotfix already executed"); require(approved, "hotfix not approved"); require(preparedEpoch == getEpochNumber(), "hotfix must be prepared for this epoch"); Proposals.makeMem(values, destinations, data, dataLengths, msg.sender, 0).executeMem(); hotfixes[hash].executed = true; emit HotfixExecuted(hash); } /** * @notice Withdraws refunded CELO deposits. * @return Whether or not the withdraw was successful. */ function withdraw() external nonReentrant returns (bool) { uint256 value = refundedDeposits[msg.sender]; require(value > 0, "Nothing to withdraw"); require(value <= address(this).balance, "Inconsistent balance"); refundedDeposits[msg.sender] = 0; msg.sender.sendValue(value); return true; } /** * @notice Returns whether or not a particular account is voting on proposals. * @param account The address of the account. * @return Whether or not the account is voting on proposals. */ function isVoting(address account) external view returns (bool) { Voter storage voter = voters[account]; uint256 upvotedProposal = voter.upvote.proposalId; bool isVotingQueue = upvotedProposal != 0 && isQueued(upvotedProposal) && !isQueuedProposalExpired(upvotedProposal); Proposals.Proposal storage proposal = proposals[voter.mostRecentReferendumProposal]; bool isVotingReferendum = (proposal.getDequeuedStage(stageDurations) == Proposals.Stage.Referendum); return isVotingQueue || isVotingReferendum; } /** * @notice Returns the number of seconds proposals stay in approval stage. * @return The number of seconds proposals stay in approval stage. */ function getApprovalStageDuration() external view returns (uint256) { return stageDurations.approval; } /** * @notice Returns the number of seconds proposals stay in the referendum stage. * @return The number of seconds proposals stay in the referendum stage. */ function getReferendumStageDuration() external view returns (uint256) { return stageDurations.referendum; } /** * @notice Returns the number of seconds proposals stay in the execution stage. * @return The number of seconds proposals stay in the execution stage. */ function getExecutionStageDuration() external view returns (uint256) { return stageDurations.execution; } /** * @notice Returns the participation parameters. * @return The participation parameters. */ function getParticipationParameters() external view returns (uint256, uint256, uint256, uint256) { return ( participationParameters.baseline.unwrap(), participationParameters.baselineFloor.unwrap(), participationParameters.baselineUpdateFactor.unwrap(), participationParameters.baselineQuorumFactor.unwrap() ); } /** * @notice Returns whether or not a proposal exists. * @param proposalId The ID of the proposal. * @return Whether or not the proposal exists. */ function proposalExists(uint256 proposalId) external view returns (bool) { return proposals[proposalId].exists(); } /** * @notice Returns an unpacked proposal struct with its transaction count. * @param proposalId The ID of the proposal to unpack. * @return The unpacked proposal with its transaction count. */ function getProposal(uint256 proposalId) external view returns (address, uint256, uint256, uint256, string memory) { return proposals[proposalId].unpack(); } /** * @notice Returns a specified transaction in a proposal. * @param proposalId The ID of the proposal to query. * @param index The index of the specified transaction in the proposal's transaction list. * @return The specified transaction. */ function getProposalTransaction(uint256 proposalId, uint256 index) external view returns (uint256, address, bytes memory) { return proposals[proposalId].getTransaction(index); } /** * @notice Returns whether or not a proposal has been approved. * @param proposalId The ID of the proposal. * @return Whether or not the proposal has been approved. */ function isApproved(uint256 proposalId) external view returns (bool) { return proposals[proposalId].isApproved(); } /** * @notice Returns the referendum vote totals for a proposal. * @param proposalId The ID of the proposal. * @return The yes, no, and abstain vote totals. */ function getVoteTotals(uint256 proposalId) external view returns (uint256, uint256, uint256) { return proposals[proposalId].getVoteTotals(); } /** * @notice Returns an accounts vote record on a particular index in `dequeued`. * @param account The address of the account to get the record for. * @param index The index in `dequeued`. * @return The corresponding proposal ID, vote value, and weight. */ function getVoteRecord(address account, uint256 index) external view returns (uint256, uint256, uint256) { VoteRecord storage record = voters[account].referendumVotes[index]; return (record.proposalId, uint256(record.value), record.weight); } /** * @notice Returns the number of proposals in the queue. * @return The number of proposals in the queue. */ function getQueueLength() external view returns (uint256) { return queue.list.numElements; } /** * @notice Returns the number of upvotes the queued proposal has received. * @param proposalId The ID of the proposal. * @return The number of upvotes a queued proposal has received. */ function getUpvotes(uint256 proposalId) external view returns (uint256) { require(isQueued(proposalId), "Proposal not queued"); return queue.getValue(proposalId); } /** * @notice Returns the proposal ID and upvote total for all queued proposals. * @return The proposal ID and upvote total for all queued proposals. * @dev Note that this includes expired proposals that have yet to be removed from the queue. */ function getQueue() external view returns (uint256[] memory, uint256[] memory) { return queue.getElements(); } /** * @notice Returns the dequeued proposal IDs. * @return The dequeued proposal IDs. * @dev Note that this includes unused indices with proposalId == 0 from deleted proposals. */ function getDequeue() external view returns (uint256[] memory) { return dequeued; } /** * @notice Returns the ID of the proposal upvoted by `account` and the weight of that upvote. * @param account The address of the account. * @return The ID of the proposal upvoted by `account` and the weight of that upvote. */ function getUpvoteRecord(address account) external view returns (uint256, uint256) { UpvoteRecord memory upvoteRecord = voters[account].upvote; return (upvoteRecord.proposalId, upvoteRecord.weight); } /** * @notice Returns the ID of the most recently dequeued proposal voted on by `account`. * @param account The address of the account. * @return The ID of the most recently dequeued proposal voted on by `account`.. */ function getMostRecentReferendumProposal(address account) external view returns (uint256) { return voters[account].mostRecentReferendumProposal; } /** * @notice Returns number of validators from current set which have whitelisted the given hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Whitelist tally */ function hotfixWhitelistValidatorTally(bytes32 hash) public view returns (uint256) { uint256 tally = 0; uint256 n = numberValidatorsInCurrentSet(); IAccounts accounts = getAccounts(); for (uint256 i = 0; i < n; i = i.add(1)) { address validatorSigner = validatorSignerAddressFromCurrentSet(i); address validatorAccount = accounts.signerToAccount(validatorSigner); if ( isHotfixWhitelistedBy(hash, validatorSigner) || isHotfixWhitelistedBy(hash, validatorAccount) ) { tally = tally.add(1); } } return tally; } /** * @notice Checks if a byzantine quorum of validators has whitelisted the given hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Whether validator whitelist tally >= validator byzantine quorum */ function isHotfixPassing(bytes32 hash) public view returns (bool) { return hotfixWhitelistValidatorTally(hash) >= minQuorumSizeInCurrentSet(); } /** * @notice Gets information about a hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Hotfix tuple of (approved, executed, preparedEpoch) */ function getHotfixRecord(bytes32 hash) public view returns (bool, bool, uint256) { return (hotfixes[hash].approved, hotfixes[hash].executed, hotfixes[hash].preparedEpoch); } /** * @notice Removes the proposals with the most upvotes from the queue, moving them to the * approval stage. * @dev If any of the top proposals have expired, they are deleted. */ function dequeueProposalsIfReady() public { // solhint-disable-next-line not-rely-on-time if (now >= lastDequeue.add(dequeueFrequency)) { uint256 numProposalsToDequeue = Math.min(concurrentProposals, queue.list.numElements); uint256[] memory dequeuedIds = queue.popN(numProposalsToDequeue); for (uint256 i = 0; i < numProposalsToDequeue; i = i.add(1)) { uint256 proposalId = dequeuedIds[i]; Proposals.Proposal storage proposal = proposals[proposalId]; if (_isQueuedProposalExpired(proposal)) { emit ProposalExpired(proposalId); continue; } refundedDeposits[proposal.proposer] = refundedDeposits[proposal.proposer].add( proposal.deposit ); // solhint-disable-next-line not-rely-on-time proposal.timestamp = now; if (emptyIndices.length > 0) { uint256 indexOfLastEmptyIndex = emptyIndices.length.sub(1); dequeued[emptyIndices[indexOfLastEmptyIndex]] = proposalId; delete emptyIndices[indexOfLastEmptyIndex]; emptyIndices.length = indexOfLastEmptyIndex; } else { dequeued.push(proposalId); } // solhint-disable-next-line not-rely-on-time emit ProposalDequeued(proposalId, now); } // solhint-disable-next-line not-rely-on-time lastDequeue = now; } } /** * @notice Returns whether or not a proposal is in the queue. * @dev NOTE: proposal may be expired * @param proposalId The ID of the proposal. * @return Whether or not the proposal is in the queue. */ function isQueued(uint256 proposalId) public view returns (bool) { return queue.contains(proposalId); } /** * @notice Returns whether or not a particular proposal is passing according to the constitution * and the participation levels. * @param proposalId The ID of the proposal. * @return Whether or not the proposal is passing. */ function isProposalPassing(uint256 proposalId) external view returns (bool) { return _isProposalPassing(proposals[proposalId]); } /** * @notice Returns whether or not a particular proposal is passing according to the constitution * and the participation levels. * @param proposal The proposal struct. * @return Whether or not the proposal is passing. */ function _isProposalPassing(Proposals.Proposal storage proposal) private view returns (bool) { FixidityLib.Fraction memory support = proposal.getSupportWithQuorumPadding( participationParameters.baseline.multiply(participationParameters.baselineQuorumFactor) ); for (uint256 i = 0; i < proposal.transactions.length; i = i.add(1)) { bytes4 functionId = ExtractFunctionSignature.extractFunctionSignature( proposal.transactions[i].data ); FixidityLib.Fraction memory threshold = _getConstitution( proposal.transactions[i].destination, functionId ); if (support.lte(threshold)) { return false; } } return true; } /** * @notice Returns whether a proposal is dequeued at the given index. * @param proposalId The ID of the proposal. * @param index The index of the proposal ID in `dequeued`. * @return Whether the proposal is in `dequeued`. */ function isDequeuedProposal(uint256 proposalId, uint256 index) external view returns (bool) { return _isDequeuedProposal(proposals[proposalId], proposalId, index); } /** * @notice Returns whether a proposal is dequeued at the given index. * @param proposal The proposal struct. * @param proposalId The ID of the proposal. * @param index The index of the proposal ID in `dequeued`. * @return Whether the proposal is in `dequeued` at index. */ function _isDequeuedProposal( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index ) private view returns (bool) { require(index < dequeued.length, "Provided index greater than dequeue length."); return proposal.exists() && dequeued[index] == proposalId; } /** * @notice Returns whether or not a dequeued proposal has expired. * @param proposalId The ID of the proposal. * @return Whether or not the dequeued proposal has expired. */ function isDequeuedProposalExpired(uint256 proposalId) external view returns (bool) { Proposals.Proposal storage proposal = proposals[proposalId]; return _isDequeuedProposalExpired(proposal, proposal.getDequeuedStage(stageDurations)); } /** * @notice Returns whether or not a dequeued proposal has expired. * @param proposal The proposal struct. * @return Whether or not the dequeued proposal has expired. */ function _isDequeuedProposalExpired(Proposals.Proposal storage proposal, Proposals.Stage stage) private view returns (bool) { // The proposal is considered expired under the following conditions: // 1. Past the approval stage and not approved. // 2. Past the referendum stage and not passing. // 3. Past the execution stage. return ((stage > Proposals.Stage.Execution) || (stage > Proposals.Stage.Referendum && !_isProposalPassing(proposal)) || (stage > Proposals.Stage.Approval && !proposal.isApproved())); } /** * @notice Returns whether or not a queued proposal has expired. * @param proposalId The ID of the proposal. * @return Whether or not the dequeued proposal has expired. */ function isQueuedProposalExpired(uint256 proposalId) public view returns (bool) { return _isQueuedProposalExpired(proposals[proposalId]); } /** * @notice Returns whether or not a queued proposal has expired. * @param proposal The proposal struct. * @return Whether or not the dequeued proposal has expired. */ function _isQueuedProposalExpired(Proposals.Proposal storage proposal) private view returns (bool) { // solhint-disable-next-line not-rely-on-time return now >= proposal.timestamp.add(queueExpiry); } /** * @notice Deletes a dequeued proposal. * @param proposal The proposal struct. * @param proposalId The ID of the proposal to delete. * @param index The index of the proposal ID in `dequeued`. * @dev Must always be preceded by `isDequeuedProposal`, which checks `index`. */ function deleteDequeuedProposal( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index ) private { if (proposal.isApproved() && proposal.networkWeight > 0) { updateParticipationBaseline(proposal); } dequeued[index] = 0; emptyIndices.push(index); delete proposals[proposalId]; } /** * @notice Updates the participation baseline based on the proportion of BondedDeposit weight * that participated in the proposal's Referendum stage. * @param proposal The proposal struct. */ function updateParticipationBaseline(Proposals.Proposal storage proposal) private { FixidityLib.Fraction memory participation = proposal.getParticipation(); FixidityLib.Fraction memory participationComponent = participation.multiply( participationParameters.baselineUpdateFactor ); FixidityLib.Fraction memory baselineComponent = participationParameters.baseline.multiply( FixidityLib.fixed1().subtract(participationParameters.baselineUpdateFactor) ); participationParameters.baseline = participationComponent.add(baselineComponent); if (participationParameters.baseline.lt(participationParameters.baselineFloor)) { participationParameters.baseline = participationParameters.baselineFloor; } emit ParticipationBaselineUpdated(participationParameters.baseline.unwrap()); } /** * @notice Returns the constitution for a particular destination and function ID. * @param destination The destination address to get the constitution for. * @param functionId The function ID to get the constitution for, zero for the destination * default. * @return The ratio of yes:no votes needed to exceed in order to pass the proposal. */ function getConstitution(address destination, bytes4 functionId) external view returns (uint256) { return _getConstitution(destination, functionId).unwrap(); } function _getConstitution(address destination, bytes4 functionId) internal view returns (FixidityLib.Fraction memory) { // Default to a simple majority. FixidityLib.Fraction memory threshold = FixidityLib.wrap(FIXED_HALF); if (constitution[destination].functionThresholds[functionId].unwrap() != 0) { threshold = constitution[destination].functionThresholds[functionId]; } else if (constitution[destination].defaultThreshold.unwrap() != 0) { threshold = constitution[destination].defaultThreshold; } return threshold; } }
* @notice Returns whether or not a dequeued proposal has expired. @param proposalId The ID of the proposal. @return Whether or not the dequeued proposal has expired./
function isDequeuedProposalExpired(uint256 proposalId) external view returns (bool) { Proposals.Proposal storage proposal = proposals[proposalId]; return _isDequeuedProposalExpired(proposal, proposal.getDequeuedStage(stageDurations)); }
5,455,411
[ 1, 1356, 2856, 578, 486, 279, 443, 19499, 14708, 711, 7708, 18, 225, 14708, 548, 1021, 1599, 434, 326, 14708, 18, 327, 17403, 578, 486, 326, 443, 19499, 14708, 711, 7708, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 353, 758, 19499, 14592, 10556, 12, 11890, 5034, 14708, 548, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 565, 1186, 22536, 18, 14592, 2502, 14708, 273, 450, 22536, 63, 685, 8016, 548, 15533, 203, 565, 327, 389, 291, 758, 19499, 14592, 10556, 12, 685, 8016, 16, 14708, 18, 588, 758, 19499, 8755, 12, 12869, 5326, 87, 10019, 203, 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 ]
./full_match/80001/0xBF6c49840EF2c86D237d55FdAF6CD51490942c5b/sources/Vault1155ERM.sol
* Clears the token filtering for a specific contract. */ Reentrancy guard. We require the contract to be frozen for extra security. Caller must be an admin. Make sure the contract is tracked. Clear the filters. Hello world!
function clearTokenFilters(address contractAddress) external { uint256 contractIndex = _coreAddressIndices[contractAddress]; require( _status == S_FROZEN && (_addressRoles[msg.sender] & R_IS_ADMIN) == R_IS_ADMIN && contractIndex > 0 , "Not authorized"); delete _filteringDataStart[contractAddress]; delete _filteringDataEnd[contractAddress]; emit FilteringCleared(contractAddress); }
866,588
[ 1, 18188, 326, 1147, 11346, 364, 279, 2923, 6835, 18, 342, 868, 8230, 12514, 11026, 18, 1660, 2583, 326, 6835, 358, 506, 12810, 364, 2870, 4373, 18, 20646, 1297, 506, 392, 3981, 18, 4344, 3071, 326, 6835, 353, 15200, 18, 10121, 326, 3415, 18, 20889, 9117, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2424, 1345, 5422, 12, 2867, 6835, 1887, 13, 3903, 288, 203, 3639, 2254, 5034, 6835, 1016, 273, 389, 3644, 1887, 8776, 63, 16351, 1887, 15533, 203, 3639, 2583, 12, 203, 5411, 389, 2327, 422, 348, 67, 42, 1457, 62, 1157, 203, 203, 5411, 597, 261, 67, 2867, 6898, 63, 3576, 18, 15330, 65, 473, 534, 67, 5127, 67, 15468, 13, 422, 534, 67, 5127, 67, 15468, 203, 203, 5411, 597, 225, 6835, 1016, 405, 374, 203, 3639, 269, 315, 1248, 10799, 8863, 203, 203, 3639, 1430, 389, 2188, 310, 751, 1685, 63, 16351, 1887, 15533, 203, 3639, 1430, 389, 2188, 310, 751, 1638, 63, 16351, 1887, 15533, 203, 203, 3639, 3626, 4008, 310, 4756, 2258, 12, 16351, 1887, 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 ]
pragma solidity ^ 0.4.19; /** * @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; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Required methods for ERC-721 Compatibility. function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns(address _owner); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns(bool); function totalSupply() public view returns(uint256 total); function balanceOf(address _owner) public view returns(uint256 _balance); } contract AnimecardAccessControl { /// @dev Event is fired when contract is forked. event ContractFork(address newContract); /// - CEO: The CEO can reassign other roles, change the addresses of dependent smart contracts, /// and pause/unpause the AnimecardCore contract. /// - CFO: The CFO can withdraw funds from its auction and sale contracts. /// - Manager: The Animator can create regular and promo AnimeCards. address public ceoAddress; address public cfoAddress; address public animatorAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked. bool public paused = false; /// @dev Access-modifier for CEO-only functionality. modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access-modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access-modifier for Animator-only functionality. modifier onlyAnimator() { require(msg.sender == animatorAddress); _; } /// @dev Access-modifier for C-level-only functionality. modifier onlyCLevel() { require( msg.sender == animatorAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// Assigns a new address to the CEO role. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// Assigns a new address to the Animator role. Only available to the current CEO. /// @param _newAnimator The address of the new Animator function setAnimator(address _newAnimator) external onlyCEO { require(_newAnimator != address(0)); animatorAddress = _newAnimator; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } /*** Destructible functionality adapted from OpenZeppelin ***/ /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyCEO public { selfdestruct(ceoAddress); } function destroyAndSend(address _recipient) onlyCEO public { selfdestruct(_recipient); } } contract AnimecardBase is AnimecardAccessControl { using SafeMath for uint256; /*** DATA TYPES ***/ /// The main anime card struct struct Animecard { /// Name of the character string characterName; /// Name of designer & studio that created the character string studioName; /// AWS S3-CDN URL for character image string characterImageUrl; /// IPFS hash of character details string characterImageHash; /// The timestamp from the block when this anime card was created uint64 creationTime; } /*** EVENTS ***/ /// The Birth event is fired whenever a new anime card comes into existence. event Birth(address owner, uint256 tokenId, string cardName, string studio); /// Transfer event as defined in current draft of ERC721. Fired every time animecard /// ownership is assigned, including births. event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /// The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 price, address prevOwner, address owner, string cardName); /*** STORAGE ***/ /// An array containing all AnimeCards in existence. The id of each animecard /// is an index in this array. Animecard[] animecards; /// @dev A mapping from anime card ids to the address that owns them. mapping(uint256 => address) public animecardToOwner; /// @dev A mapping from owner address to count of anime cards that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping(address => uint256) public ownerAnimecardCount; /// @dev A mapping from anime card ids to an address that has been approved to call /// transferFrom(). Each anime card can only have 1 approved address for transfer /// at any time. A 0 value means no approval is outstanding. mapping(uint256 => address) public animecardToApproved; // @dev A mapping from anime card ids to their price. mapping(uint256 => uint256) public animecardToPrice; // @dev Previous sale price of anime card mapping(uint256 => uint256) public animecardPrevPrice; /// @dev Assigns ownership of a specific anime card to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Transfer ownership and update owner anime card counts. // ownerAnimecardCount[_to] = ownerAnimecardCount[_to].add(1); ownerAnimecardCount[_to]++; animecardToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { // ownerAnimecardCount[_from] = ownerAnimecardCount[_from].sub(1); ownerAnimecardCount[_from]--; // clear any previously approved ownership exchange delete animecardToApproved[_tokenId]; } // Fire the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new anime card and stores it. /// @param _characterName The name of the character /// @param _studioName The studio that created this character /// @param _characterImageUrl AWS S3-CDN URL for character image /// @param _characterImageHash IPFS hash for character image /// @param _price of animecard character /// @param _owner The initial owner of this anime card function _createAnimecard( string _characterName, string _studioName, string _characterImageUrl, string _characterImageHash, uint256 _price, address _owner ) internal returns(uint) { Animecard memory _animecard = Animecard({ characterName: _characterName, studioName: _studioName, characterImageUrl: _characterImageUrl, characterImageHash: _characterImageHash, creationTime: uint64(now) }); uint256 newAnimecardId = animecards.push(_animecard); newAnimecardId = newAnimecardId.sub(1); // Fire the birth event. Birth( _owner, newAnimecardId, _animecard.characterName, _animecard.studioName ); // Set the price for the animecard. animecardToPrice[newAnimecardId] = _price; // This will assign ownership, and also fire the Transfer event as per ERC-721 draft. _transfer(0, _owner, newAnimecardId); return newAnimecardId; } } contract AnimecardPricing is AnimecardBase { /*** CONSTANTS ***/ // Pricing steps. uint256 private constant first_step_limit = 0.05 ether; uint256 private constant second_step_limit = 0.5 ether; uint256 private constant third_step_limit = 2.0 ether; uint256 private constant fourth_step_limit = 5.0 ether; // Cut for studio & platform for each sale transaction uint256 public platformFee = 50; // 50% /// @dev Set Studio Fee. Can only be called by the Animator address. function setPlatformFee(uint256 _val) external onlyAnimator { platformFee = _val; } /// @dev Computes next price of token given the current sale price. function computeNextPrice(uint256 _salePrice) internal pure returns(uint256) { if (_salePrice < first_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 200), 100); } else if (_salePrice < second_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 135), 100); } else if (_salePrice < third_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 125), 100); } else if (_salePrice < fourth_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 120), 100); } else { return SafeMath.div(SafeMath.mul(_salePrice, 115), 100); } } /// @dev Computes the payment for the token, which is the sale price of the token /// minus the house's cut. function computePayment( uint256 _tokenId, uint256 _salePrice) internal view returns(uint256) { uint256 prevSalePrice = animecardPrevPrice[_tokenId]; uint256 profit = _salePrice - prevSalePrice; uint256 ownerCut = SafeMath.sub(100, platformFee); uint256 ownerProfitShare = SafeMath.div(SafeMath.mul(profit, ownerCut), 100); return prevSalePrice + ownerProfitShare; } } contract AnimecardOwnership is AnimecardPricing, ERC721 { /// Name of the collection of NFTs managed by this contract, as defined in ERC721. string public constant NAME = "CryptoAnime"; /// Symbol referencing the entire collection of NFTs managed in this contract, as /// defined in ERC721. string public constant SYMBOL = "ANM"; bytes4 public constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /*** EVENTS ***/ /// Approval event as defined in the current draft of ERC721. Fired every time /// animecard approved owners is updated. When Transfer event is emitted, this /// also indicates that approved address is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns(bool) { return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721)); } // @notice Optional for ERC-20 compliance. function name() external pure returns(string) { return NAME; } // @notice Optional for ERC-20 compliance. function symbol() external pure returns(string) { return SYMBOL; } /// @dev Returns the total number of Animecards currently in existence. /// @notice Required for ERC-20 and ERC-721 compliance. function totalSupply() public view returns(uint) { return animecards.length; } /// @dev Returns the number of Animecards owned by a specific address. /// @param _owner The owner address to check. /// @notice Required for ERC-20 and ERC-721 compliance. function balanceOf(address _owner) public view returns(uint256 count) { return ownerAnimecardCount[_owner]; } /// @dev Returns the address currently assigned ownership of a given Animecard. /// @notice Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns(address _owner) { _owner = animecardToOwner[_tokenId]; require(_owner != address(0)); } /// @dev Grant another address the right to transfer a specific Anime card via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Animecard that can be transferred if this call succeeds. /// @notice Required for ERC-20 and ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Fire approval event upon successful approval. Approval(msg.sender, _to, _tokenId); } /// @dev Transfers a Animecard to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 or else your /// Animecard may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Animecard to transfer. /// @notice Required for ERC-20 and ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any animecard (except very briefly // after a Anime card is created). require(_to != address(this)); // You can only transfer your own Animecard. require(_owns(msg.sender, _tokenId)); // TODO - Disallow transfer to self // Reassign ownership, clear pending approvals, fire Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @dev Transfer a Animecard owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Animecard to be transfered. /// @param _to The address that should take ownership of the Animecard. Can be any /// address, including the caller. /// @param _tokenId The ID of the Animecard to be transferred. /// @notice Required for ERC-20 and ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any animecard (except very briefly // after an animecard is created). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and fires Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Returns a list of all Animecard IDs assigned to an address. /// @param _owner The owner whose Animecards we are interested in. /// This method MUST NEVER be called by smart contract code. First, it is fairly /// expensive (it walks the entire Animecard array looking for Animecard belonging /// to owner), but it also returns a dynamic array, which is only supported for web3 /// calls, and not contract-to-contract calls. Thus, this method is external rather /// than public. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Returns an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalAnimecards = totalSupply(); uint256 resultIndex = 0; uint256 animecardId; for (animecardId = 0; animecardId <= totalAnimecards; animecardId++) { if (animecardToOwner[animecardId] == _owner) { result[resultIndex] = animecardId; resultIndex++; } } return result; } } /// @dev Checks if a given address is the current owner of a particular Animecard. /// @param _claimant the address we are validating against. /// @param _tokenId Animecard id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns(bool) { return animecardToOwner[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Animecards on sale and, /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { animecardToApproved[_tokenId] = _approved; } /// @dev Checks if a given address currently has transferApproval for a particular /// Animecard. /// @param _claimant the address we are confirming Animecard is approved for. /// @param _tokenId Animecard id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns(bool) { return animecardToApproved[_tokenId] == _claimant; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns(bool) { return _to != address(0); } } contract AnimecardSale is AnimecardOwnership { // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable whenNotPaused { address newOwner = msg.sender; address oldOwner = animecardToOwner[_tokenId]; uint256 salePrice = animecardToPrice[_tokenId]; // Require that the owner of the token is not sending to self. require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Check that sent amount is greater than or equal to the sale price require(msg.value >= salePrice); uint256 payment = uint256(computePayment(_tokenId, salePrice)); uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice); // Set next listing price. animecardPrevPrice[_tokenId] = animecardToPrice[_tokenId]; animecardToPrice[_tokenId] = computeNextPrice(salePrice); // Transfer the Animecard to the buyer. _transfer(oldOwner, newOwner, _tokenId); // Pay seller of the Animecard if they are not this contract. if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, salePrice, animecardToPrice[_tokenId], oldOwner, newOwner, animecards[_tokenId].characterName); // Reimburse the buyer of any excess paid. msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns(uint256 price) { return animecardToPrice[_tokenId]; } } contract AnimecardMinting is AnimecardSale { /*** CONSTANTS ***/ /// @dev Starting price of a regular Animecard. // uint128 private constant STARTING_PRICE = 0.01 ether; /// @dev Creates a new Animecard function createAnimecard( string _characterName, string _studioName, string _characterImageUrl, string _characterImageHash, uint256 _price ) public onlyAnimator returns(uint) { uint256 animecardId = _createAnimecard( _characterName, _studioName, _characterImageUrl, _characterImageHash, _price, address(this) ); return animecardId; } } // Cryptoanime: Anime collectibles on blockchain contract AnimecardCore is AnimecardMinting { // contract AnimecardCore is AnimecardMinting { // Set in case the core contract is broken and a fork is required address public newContractAddress; function AnimecardCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Animator animatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes both the studio fee /// and blockpunk fee on every animecard sold and any Ether sent directly to /// contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific animecard. /// @param _tokenId The tokenId of the animecard of interest. function getAnimecard(uint256 _tokenId) external view returns( string characterName, string studioName, string characterImageUrl, string characterImageHash, uint256 sellingPrice, address owner) { Animecard storage animecard = animecards[_tokenId]; characterName = animecard.characterName; studioName = animecard.studioName; characterImageUrl = animecard.characterImageUrl; characterImageHash = animecard.characterImageHash; sellingPrice = animecardToPrice[_tokenId]; owner = animecardToOwner[_tokenId]; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } /// @notice Direct donations function () external payable {} }
@dev Returns the total number of Animecards currently in existence. @notice Required for ERC-20 and ERC-721 compliance.
function totalSupply() public view returns(uint) { return animecards.length; }
5,525,940
[ 1, 1356, 326, 2078, 1300, 434, 1922, 494, 3327, 87, 4551, 316, 15782, 18, 225, 10647, 364, 4232, 39, 17, 3462, 471, 4232, 39, 17, 27, 5340, 29443, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 392, 494, 3327, 87, 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, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface ICurvePairs { function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external; function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 _min_amount) external; function balances(uint256 i) external view returns (uint256); } interface IGauge { function balanceOf(address _address) external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getReward() external; // For Pickle Farm only } interface IMintr { function mint(address _address) external; } interface IRouter { 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 removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } interface IPickleJar is IERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function balance() external view returns (uint256); } interface IMasterChef { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint256, address) external view returns(uint256, uint256); } interface IWETH is IERC20 { function withdraw(uint256 _amount) external; } interface ICitadelVault { function getReimburseTokenAmount(uint256) external view returns (uint256); } interface IChainlink { function latestAnswer() external view returns (int256); } interface ISLPToken is IERC20 { function getReserves() external view returns (uint112, uint112, uint32); } contract CitadelStrategy is Ownable { using SafeERC20 for IERC20; using SafeERC20 for IWETH; using SafeERC20 for IPickleJar; using SafeERC20 for ISLPToken; using SafeMath for uint256; IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IRouter private constant router = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiSwap ICitadelVault public vault; // Curve ICurvePairs private constant cPairs = ICurvePairs(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F); // HBTC/WBTC IERC20 private constant clpToken = IERC20(0xb19059ebb43466C323583928285a49f558E572Fd); IERC20 private constant CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IGauge private constant gaugeC = IGauge(0x4c18E409Dc8619bFb6a1cB56D114C3f592E0aE79); IMintr private constant mintr = IMintr(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // Pickle ISLPToken private constant slpWBTC = ISLPToken(0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58); // WBTC/ETH ISLPToken private constant slpDAI = ISLPToken(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f); // DAI/ETH IERC20 private constant PICKLE = IERC20(0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5); IPickleJar private constant pickleJarWBTC = IPickleJar(0xde74b6c547bd574c3527316a2eE30cd8F6041525); IPickleJar private constant pickleJarDAI = IPickleJar(0x55282dA27a3a02ffe599f6D11314D239dAC89135); IGauge private constant gaugeP_WBTC = IGauge(0xD55331E7bCE14709d825557E5Bca75C73ad89bFb); IGauge private constant gaugeP_DAI = IGauge(0x6092c7084821057060ce2030F9CC11B22605955F); // Sushiswap Onsen IERC20 private constant DPI = IERC20(0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b); ISLPToken private constant slpDPI = ISLPToken(0x34b13F8CD184F55d0Bd4Dd1fe6C07D46f245c7eD); // DPI/ETH IERC20 private constant SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); IMasterChef private constant masterChef = IMasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd); // LP token price in ETH uint256 private _HBTCWBTCLPTokenPrice; uint256 private _WBTCETHLPTokenPrice; uint256 private _DPIETHLPTokenPrice; uint256 private _DAIETHLPTokenPrice; // Pool in ETH uint256 private _poolHBTCWBTC; uint256 private _poolWBTCETH; uint256 private _poolDPIETH; uint256 private _poolDAIETH; uint256 private _pool; // For emergencyWithdraw() only // Others uint256 private constant DENOMINATOR = 10000; bool public isVesting; // Fees uint256 public yieldFeePerc = 1000; address public admin; address public communityWallet; address public strategist; event ETHToInvest(uint256 amount); event LatestLPTokenPrice(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); event YieldAmount(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH event CurrentComposition(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH event TargetComposition(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH event AddLiquidity(address pairs, uint256 amountA, uint256 amountB, uint256 lpTokenMinted); // in ETH modifier onlyVault { require(msg.sender == address(vault), "Only vault"); _; } constructor(address _communityWallet, address _strategist, address _admin) { communityWallet = _communityWallet; strategist = _strategist; admin = _admin; // Sushiswap router WETH.safeApprove(address(router), type(uint256).max); WBTC.safeApprove(address(router), type(uint256).max); DAI.safeApprove(address(router), type(uint256).max); slpWBTC.safeApprove(address(router), type(uint256).max); slpDAI.safeApprove(address(router), type(uint256).max); slpDPI.safeApprove(address(router), type(uint256).max); CRV.safeApprove(address(router), type(uint256).max); PICKLE.safeApprove(address(router), type(uint256).max); SUSHI.safeApprove(address(router), type(uint256).max); // Curve WBTC.safeApprove(address(cPairs), type(uint256).max); clpToken.safeApprove(address(gaugeC), type(uint256).max); // Pickle slpWBTC.safeApprove(address(pickleJarWBTC), type(uint256).max); slpDAI.safeApprove(address(pickleJarDAI), type(uint256).max); pickleJarWBTC.safeApprove(address(gaugeP_WBTC), type(uint256).max); pickleJarDAI.safeApprove(address(gaugeP_DAI), type(uint256).max); // Sushiswap Onsen DPI.safeApprove(address(router), type(uint256).max); slpDPI.safeApprove(address(masterChef), type(uint256).max); // Set first LP tokens price (uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice(); _HBTCWBTCLPTokenPrice = _clpTokenPriceHBTC; _WBTCETHLPTokenPrice = _pSlpTokenPriceWBTC; _DPIETHLPTokenPrice = _slpTokenPriceDPI; _DAIETHLPTokenPrice = _pSlpTokenPriceDAI; } /// @notice Function to set vault address that interact with this contract. This function only execute once when deployment /// @param _address Address of vault contract function setVault(address _address) external onlyOwner { require(address(vault) == address(0), "Vault set"); vault = ICitadelVault(_address); } /// @notice Function to invest new funds to farms based on composition /// @param _amount Amount to invest in ETH function invest(uint256 _amount) external onlyVault { _updatePoolForPriceChange(); WETH.safeTransferFrom(address(vault), address(this), _amount); emit ETHToInvest(_amount); _updatePoolForProvideLiquidity(); } /// @notice Function to update pool balance because of price change of corresponding LP token function _updatePoolForPriceChange() private { (uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice(); _poolHBTCWBTC = _poolHBTCWBTC.mul(_clpTokenPriceHBTC).div(_HBTCWBTCLPTokenPrice); _poolWBTCETH = _poolWBTCETH.mul(_pSlpTokenPriceWBTC).div(_WBTCETHLPTokenPrice); _poolDPIETH = _poolDPIETH.mul(_slpTokenPriceDPI).div(_DPIETHLPTokenPrice); _poolDAIETH = _poolDAIETH.mul(_pSlpTokenPriceDAI).div(_DAIETHLPTokenPrice); emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH); // Update new LP token price _HBTCWBTCLPTokenPrice = _clpTokenPriceHBTC; _WBTCETHLPTokenPrice = _pSlpTokenPriceWBTC; _DPIETHLPTokenPrice = _slpTokenPriceDPI; _DAIETHLPTokenPrice = _pSlpTokenPriceDAI; emit LatestLPTokenPrice(_HBTCWBTCLPTokenPrice, _WBTCETHLPTokenPrice, _DPIETHLPTokenPrice, _DAIETHLPTokenPrice); } /// @notice Function to harvest rewards from farms and reinvest into farms based on composition function yield() external onlyVault { _updatePoolForPriceChange(); uint256[] memory _yieldAmts = new uint256[](4); // For emit yield amount of each farm // 1) Claim all rewards uint256 _yieldFees; // Curve HBTC/WBTC mintr.mint(address(gaugeC)); // Claim CRV uint256 _balanceOfCRV = CRV.balanceOf(address(this)); if (_balanceOfCRV > 0) { uint256[] memory _amounts = _swapExactTokensForTokens(address(CRV), address(WETH), _balanceOfCRV); _yieldAmts[0] = _amounts[1]; uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR); _poolHBTCWBTC = _poolHBTCWBTC.add(_amounts[1].sub(_fee)); _yieldFees = _yieldFees.add(_fee); } // Pickle WBTC/ETH gaugeP_WBTC.getReward(); // Claim PICKLE uint256 _balanceOfPICKLEForWETH = PICKLE.balanceOf(address(this)); if (_balanceOfPICKLEForWETH > 0) { uint256[] memory _amounts = _swapExactTokensForTokens(address(PICKLE), address(WETH), _balanceOfPICKLEForWETH); _yieldAmts[1] = _amounts[1]; uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR); _poolWBTCETH = _poolWBTCETH.add(_amounts[1].sub(_fee)); _yieldFees = _yieldFees.add(_fee); } // Sushiswap DPI/ETH (uint256 _slpDPIAmt,) = masterChef.userInfo(42, address(this)); if (_slpDPIAmt > 0) { // SushiSwap previous SUSHI reward is auto harvest after new deposit // Swap SUSHI to WETH uint256 _balanceOfSUSHI = SUSHI.balanceOf(address(this)); if (_balanceOfSUSHI > 0) { uint256[] memory _amounts = _swapExactTokensForTokens(address(SUSHI), address(WETH), _balanceOfSUSHI); uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR); _yieldAmts[2] = _amounts[1]; _poolDPIETH = _poolDPIETH.add(_amounts[1].sub(_fee)); _yieldFees = _yieldFees.add(_fee); } } // Pickle DAI/ETH gaugeP_DAI.getReward(); // Claim PICKLE uint256 _balanceOfPICKLEForDAI = PICKLE.balanceOf(address(this)); if (_balanceOfPICKLEForDAI > 0) { uint256[] memory _amounts = _swapExactTokensForTokens(address(PICKLE), address(WETH), _balanceOfPICKLEForDAI); _yieldAmts[3] = _amounts[1]; uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR); _poolDAIETH = _poolDAIETH.add(_amounts[1].sub(_fee)); _yieldFees = _yieldFees.add(_fee); } emit YieldAmount(_yieldAmts[0], _yieldAmts[1], _yieldAmts[2], _yieldAmts[3]); // 2) Split yield fees _splitYieldFees(_yieldFees); // 3) Reinvest rewards _updatePoolForProvideLiquidity(); } /// @notice Function to transfer fees that collect from yield to wallets /// @param _amount Fees to transfer in ETH function _splitYieldFees(uint256 _amount) private { WETH.withdraw(_amount); uint256 _yieldFee = (address(this).balance).mul(2).div(5); (bool _a,) = admin.call{value: _yieldFee}(""); // 40% require(_a); (bool _t,) = communityWallet.call{value: _yieldFee}(""); // 40% require(_t); (bool _s,) = strategist.call{value: (address(this).balance)}(""); // 20% require(_s); } // To enable receive ETH from WETH in _splitYieldFees() receive() external payable {} /// @notice Function to provide liquidity into farms and update pool of each farms function _updatePoolForProvideLiquidity() private { uint256 _totalPool = _getTotalPool().add(WETH.balanceOf(address(this))); // Calculate target composition for each farm uint256 _thirtyPercOfPool = _totalPool.mul(3000).div(DENOMINATOR); uint256 _poolHBTCWBTCTarget = _thirtyPercOfPool; // 30% for Curve HBTC/WBTC uint256 _poolWBTCETHTarget = _thirtyPercOfPool; // 30% for Pickle WBTC/ETH uint256 _poolDPIETHTarget = _thirtyPercOfPool; // 30% for SushiSwap DPI/ETH uint256 _poolDAIETHTarget = _totalPool.sub(_thirtyPercOfPool).sub(_thirtyPercOfPool).sub(_thirtyPercOfPool); // 10% for Pickle DAI/ETH emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH); emit TargetComposition(_poolHBTCWBTCTarget, _poolWBTCETHTarget, _poolDPIETHTarget, _poolDAIETHTarget); // If there is no negative value(need to remove liquidity from farm in order to drive back the composition) // We proceed with split funds into 4 farms and drive composition back to target // Else, we put all the funds into the farm that is furthest from target composition if ( _poolHBTCWBTCTarget > _poolHBTCWBTC && _poolWBTCETHTarget > _poolWBTCETH && _poolDPIETHTarget > _poolDPIETH && _poolDAIETHTarget > _poolDAIETH ) { // invest funds into Curve HBTC/WBTC uint256 _investHBTCWBTCAmt = _poolHBTCWBTCTarget.sub(_poolHBTCWBTC); _investHBTCWBTC(_investHBTCWBTCAmt); // invest funds into Pickle WBTC/ETH uint256 _investWBTCETHAmt = _poolWBTCETHTarget.sub(_poolWBTCETH); _investWBTCETH(_investWBTCETHAmt); // invest funds into Sushiswap Onsen DPI/ETH uint256 _investDPIETHAmt = _poolDPIETHTarget.sub(_poolDPIETH); _investDPIETH(_investDPIETHAmt); // invest funds into Pickle DAI/ETH uint256 _investDAIETHAmt = _poolDAIETHTarget.sub(_poolDAIETH); _investDAIETH(_investDAIETHAmt); } else { // Put all the yield into the farm that is furthest from target composition uint256 _furthest; uint256 _farmIndex; // 1. Find out the farm that is furthest from target composition if (_poolHBTCWBTCTarget > _poolHBTCWBTC) { uint256 _diff = _poolHBTCWBTCTarget.sub(_poolHBTCWBTC); _furthest = _diff; _farmIndex = 0; } if (_poolWBTCETHTarget > _poolWBTCETH) { uint256 _diff = _poolWBTCETHTarget.sub(_poolWBTCETH); if (_diff > _furthest) { _furthest = _diff; _farmIndex = 1; } } if (_poolDPIETHTarget > _poolDPIETH) { uint256 _diff = _poolDPIETHTarget.sub(_poolDPIETH); if (_diff > _furthest) { _furthest = _diff; _farmIndex = 2; } } if (_poolDAIETHTarget > _poolDAIETH) { uint256 _diff = _poolDAIETHTarget.sub(_poolDAIETH); if (_diff > _furthest) { _furthest = _diff; _farmIndex = 3; } } // 2. Put all the funds into the farm that is furthest from target composition uint256 _balanceOfWETH = WETH.balanceOf(address(this)); if (_farmIndex == 0) { _investHBTCWBTC(_balanceOfWETH); } else if (_farmIndex == 1) { _investWBTCETH(_balanceOfWETH); } else if (_farmIndex == 2) { _investDPIETH(_balanceOfWETH); } else { _investDAIETH(_balanceOfWETH); } } emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH); } /// @notice Function to invest funds into Curve HBTC/WBTC pool /// @notice and stake Curve LP token into Curve Gauge(staking contract) /// @param _amount Amount to invest in ETH function _investHBTCWBTC(uint256 _amount) private { uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(WBTC), _amount); if (_amounts[1] > 0) { cPairs.add_liquidity([0, _amounts[1]], 0); uint256 _balanceOfClpToken = clpToken.balanceOf(address(this)); gaugeC.deposit(_balanceOfClpToken); _poolHBTCWBTC = _poolHBTCWBTC.add(_amount); emit AddLiquidity(address(cPairs), _amounts[1], 0, _balanceOfClpToken); } } /// @notice Function to invest funds into SushiSwap WBTC/ETH pool, deposit SLP token into Pickle Jar(vault contract) /// @notice and stake Pickle LP token into Pickle Farm(staking contract) /// @param _amount Amount to invest in ETH function _investWBTCETH(uint256 _amount) private { uint256 _amountIn = _amount.div(2); uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(WBTC), _amountIn); if (_amounts[1] > 0) { (uint256 _amountA, uint256 _amountB, uint256 _slpWBTC) = router.addLiquidity( address(WBTC), address(WETH), _amounts[1], _amountIn, 0, 0, address(this), block.timestamp ); emit AddLiquidity(address(slpWBTC), _amountA, _amountB, _slpWBTC); pickleJarWBTC.deposit(_slpWBTC); gaugeP_WBTC.deposit(pickleJarWBTC.balanceOf(address(this))); _poolWBTCETH = _poolWBTCETH.add(_amount); } } /// @notice Function to invest funds into SushiSwap DPI/ETH pool /// @notice and stake SLP token into SushiSwap MasterChef(staking contract) /// @param _amount Amount to invest in ETH function _investDPIETH(uint256 _amount) private { uint256 _amountIn = _amount.div(2); uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(DPI), _amountIn); if (_amounts[1] > 0) { (uint256 _amountA, uint256 _amountB, uint256 _slpDPI) = router.addLiquidity(address(DPI), address(WETH), _amounts[1], _amountIn, 0, 0, address(this), block.timestamp); masterChef.deposit(42, _slpDPI); _poolDPIETH = _poolDPIETH.add(_amount); emit AddLiquidity(address(slpDPI), _amountA, _amountB, _slpDPI); } } /// @notice Function to invest funds into SushiSwap DAI/ETH pool, deposit SLP token into Pickle Jar(vault contract) /// @notice and stake Pickle LP token into Pickle Farm(staking contract) /// @param _amount Amount to invest in ETH function _investDAIETH(uint256 _amount) private { uint256 _amountIn = _amount.div(2); uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(DAI), _amountIn); if (_amounts[1] > 0) { (uint256 _amountA, uint256 _amountB, uint256 _slpDAI) = router.addLiquidity( address(DAI), address(WETH), _amounts[1], _amountIn, 0, 0, address(this), block.timestamp ); emit AddLiquidity(address(slpDAI), _amountA, _amountB, _slpDAI); // 1389.083912192186144530 0.335765206816332767 17.202418926243352766 pickleJarDAI.deposit(_slpDAI); gaugeP_DAI.deposit(pickleJarDAI.balanceOf(address(this))); _poolDAIETH = _poolDAIETH.add(_amount); } } // @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms function reimburse() external onlyVault { // Get total reimburse amount (6 decimals) uint256 _reimburseUSDT = vault.getReimburseTokenAmount(0); uint256 _reimburseUSDC = vault.getReimburseTokenAmount(1); uint256 _reimburseDAI = vault.getReimburseTokenAmount(2); uint256 _totalReimburse = _reimburseUSDT.add(_reimburseUSDC).add(_reimburseDAI.div(1e12)); // Get ETH needed from farm (by removing liquidity then swap to ETH) uint256[] memory _amounts = router.getAmountsOut(_totalReimburse, _getPath(address(USDT), address(WETH))); if (WETH.balanceOf(address(this)) < _amounts[1]) { // Balance of WETH > _amounts[1] when execute emergencyWithdraw() _updatePoolForPriceChange(); uint256 _thirtyPercOfAmtWithdraw = _amounts[1].mul(3000).div(DENOMINATOR); _withdrawCurve(_thirtyPercOfAmtWithdraw); // 30% from Curve HBTC/WBTC _withdrawPickleWBTC(_thirtyPercOfAmtWithdraw); // 30% from Pickle WBTC/ETH _withdrawSushiswap(_thirtyPercOfAmtWithdraw); // 30% from SushiSwap DPI/ETH _withdrawPickleDAI(_amounts[1].sub(_thirtyPercOfAmtWithdraw).sub(_thirtyPercOfAmtWithdraw).sub(_thirtyPercOfAmtWithdraw)); // 10% from Pickle DAI/ETH _swapAllToETH(); // Swap WBTC, DPI & DAI that get from withdrawal above to WETH } // Swap WETH to token and transfer back to vault uint256 _WETHBalance = WETH.balanceOf(address(this)); _reimburse(_WETHBalance.mul(_reimburseUSDT).div(_totalReimburse), USDT); _reimburse(_WETHBalance.mul(_reimburseUSDC).div(_totalReimburse), USDC); _reimburse((WETH.balanceOf(address(this))), DAI); } /// @notice reimburse() nested function /// @param _reimburseAmt Amount to reimburse in ETH /// @param _token Type of token to reimburse function _reimburse(uint256 _reimburseAmt, IERC20 _token) private { if (_reimburseAmt > 0) { uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(_token), _reimburseAmt); _token.safeTransfer(address(vault), _amounts[1]); } } /// @notice Function to withdraw all funds from all farms function emergencyWithdraw() external onlyVault { // 1. Withdraw all token from all farms // Since to withdraw all funds, there is no need to _updatePoolForPriceChange() // Curve HBTC/WBTC mintr.mint(address(gaugeC)); _withdrawCurve(_poolHBTCWBTC); // Pickle WBTC/ETH gaugeP_WBTC.getReward(); _withdrawPickleWBTC(_poolWBTCETH); // Sushiswap DPI/ETH _withdrawSushiswap(_poolDPIETH); // Pickle DAI/ETH gaugeP_WBTC.getReward(); _withdrawPickleDAI(_poolDAIETH); // 2.1 Swap all rewards to WETH uint256 balanceOfWETHBefore = WETH.balanceOf(address(this)); _swapExactTokensForTokens(address(CRV), address(WETH), CRV.balanceOf(address(this))); _swapExactTokensForTokens(address(PICKLE), address(WETH), PICKLE.balanceOf(address(this))); _swapExactTokensForTokens(address(SUSHI), address(WETH), SUSHI.balanceOf(address(this))); // Send portion rewards to admin uint256 _rewards = (WETH.balanceOf(address(this))).sub(balanceOfWETHBefore); uint256 _adminFees = _rewards.mul(yieldFeePerc).div(DENOMINATOR); _splitYieldFees(_adminFees); // 2.2 Swap WBTC, DPI & DAI to WETH _swapAllToETH(); _pool = WETH.balanceOf(address(this)); isVesting = true; } /// @notice Function to invest back WETH into farms after emergencyWithdraw() function reinvest() external onlyVault { _pool = 0; isVesting = false; _updatePoolForProvideLiquidity(); } /// @notice Function to swap tokens with SushiSwap /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @param _amountIn Amount of token to be swapped /// @return _amounts Array that contains swapped amounts function _swapExactTokensForTokens(address _tokenA, address _tokenB, uint256 _amountIn) private returns (uint256[] memory _amounts) { address[] memory _path = _getPath(_tokenA, _tokenB); uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path); if (_amountsOut[1] > 0) { _amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[1] = 0; return _zeroReturn; } } /// @notice Function to withdraw funds from farms if withdraw amount > amount keep in vault /// @param _amount Amount to withdraw in ETH function withdraw(uint256 _amount) external onlyVault { if (!isVesting) { // Update to latest pool _updatePoolForPriceChange(); uint256 _totalPool = _getTotalPool(); // _WETHAmtBefore: Need this because there will be leftover after provide liquidity to farms uint256 _WETHAmtBefore = WETH.balanceOf(address(this)); // Withdraw from Curve HBTC/WBTC _withdrawCurve(_poolHBTCWBTC.mul(_amount).div(_totalPool)); // Withdraw from Pickle WBTC/ETH _withdrawPickleWBTC(_poolWBTCETH.mul(_amount).div(_totalPool)); // Withdraw from Sushiswap DPI/ETH _withdrawSushiswap(_poolDPIETH.mul(_amount).div(_totalPool)); // Withdraw from Pickle DAI/ETH _withdrawPickleDAI(_poolDAIETH.mul(_amount).div(_totalPool)); _swapAllToETH(); // Swap WBTC, DPI & DAI that get from withdrawal above to WETH WETH.safeTransfer(msg.sender, (WETH.balanceOf(address(this))).sub(_WETHAmtBefore)); } else { _pool = _pool.sub(_amount); WETH.safeTransfer(msg.sender, _amount); } } /// @notice Function to unstake LP token(gaugeC) and remove liquidity(cPairs) from Curve /// @param _amount Amount to withdraw in ETH function _withdrawCurve(uint256 _amount) private { uint256 _totalClpToken = gaugeC.balanceOf(address(this)); uint256 _clpTokenShare = _totalClpToken.mul(_amount).div(_poolHBTCWBTC); gaugeC.withdraw(_clpTokenShare); cPairs.remove_liquidity_one_coin(_clpTokenShare, 1, 0); _poolHBTCWBTC = _poolHBTCWBTC.sub(_amount); } /// @notice Function to unstake LP token from Pickle Farm(gaugeP_WBTC), /// @notice withdraw from Pickle Jar(pickleJarWBTC), /// @notice and remove liquidity(router) from SushiSwap /// @param _amount Amount to withdraw in ETH function _withdrawPickleWBTC(uint256 _amount) private { uint256 _totalPlpToken = gaugeP_WBTC.balanceOf(address(this)); uint256 _plpTokenShare = _totalPlpToken.mul(_amount).div(_poolWBTCETH); gaugeP_WBTC.withdraw(_plpTokenShare); pickleJarWBTC.withdraw(_plpTokenShare); router.removeLiquidity(address(WBTC), address(WETH), slpWBTC.balanceOf(address(this)), 0, 0, address(this), block.timestamp); _poolWBTCETH = _poolWBTCETH.sub(_amount); } /// @notice Function to unstake LP token(masterChef) and remove liquidity(router) from SushiSwap /// @param _amount Amount to withdraw in ETH function _withdrawSushiswap(uint256 _amount) private { (uint256 _totalSlpToken,) = masterChef.userInfo(42, address(this)); uint256 _slpTokenShare = _totalSlpToken.mul(_amount).div(_poolDPIETH); masterChef.withdraw(42, _slpTokenShare); router.removeLiquidity(address(DPI), address(WETH), _slpTokenShare, 0, 0, address(this), block.timestamp); _poolDPIETH = _poolDPIETH.sub(_amount); } /// @notice Function to unstake LP token from Pickle Farm(gaugeP_DAI), /// @notice withdraw from Pickle Jar(pickleJarDAI), /// @notice and remove liquidity(router) from SushiSwap /// @param _amount Amount to withdraw in ETH function _withdrawPickleDAI(uint256 _amount) private { uint256 _totalPlpToken = gaugeP_DAI.balanceOf(address(this)); uint256 _plpTokenShare = _totalPlpToken.mul(_amount).div(_poolDAIETH); gaugeP_DAI.withdraw(_plpTokenShare); pickleJarDAI.withdraw(_plpTokenShare); router.removeLiquidity(address(DAI), address(WETH), slpDAI.balanceOf(address(this)), 0, 0, address(this), block.timestamp); _poolDAIETH = _poolDAIETH.sub(_amount); } /// @notice Function to swap tokens that receive by removing liquidity for all farms function _swapAllToETH() private { _swapExactTokensForTokens(address(WBTC), address(WETH), WBTC.balanceOf(address(this))); _swapExactTokensForTokens(address(DPI), address(WETH), DPI.balanceOf(address(this))); _swapExactTokensForTokens(address(DAI), address(WETH), DAI.balanceOf(address(this))); } /// @notice Function to set new admin address from vault contract /// @param _admin Address of new admin function setAdmin(address _admin) external onlyVault { admin = _admin; } /// @notice Function to set new strategist address from vault contract /// @param _strategist Address of new strategist function setStrategist(address _strategist) external onlyVault { strategist = _strategist; } /// @notice Function to approve vault to migrate funds from this contract to new strategy contract function approveMigrate() external onlyOwner { require(isVesting, "Not in vesting state"); if (WETH.allowance(address(this), address(vault)) == 0) { WETH.safeApprove(address(vault), type(uint256).max); } } /// @notice Function to get path for SushiSwap swap functions /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @return _path Array of address function _getPath(address _tokenA, address _tokenB) private pure returns (address[] memory) { address[] memory _path = new address[](2); _path[0] = _tokenA; _path[1] = _tokenB; return _path; } /// @notice Function to get latest LP token price for all farms /// @return All LP token price in ETH function _getLPTokenPrice() private view returns (uint256, uint256, uint256, uint256) { // 1. Get tokens price in ETH uint256 _wbtcPrice = (router.getAmountsOut(1e8, _getPath(address(WBTC), address(WETH))))[1]; uint256 _dpiPrice = _getTokenPriceFromChainlink(0x029849bbc0b1d93b85a8b6190e979fd38F5760E2); // DPI/ETH uint256 _daiPrice = _getTokenPriceFromChainlink(0x773616E4d11A78F511299002da57A0a94577F1f4); // DAI/ETH // 2. Calculate LP token price // Curve HBTC/WBTC uint256 _amountACurve = cPairs.balances(0); // HBTC, 18 decimals uint256 _amountBCurve = (cPairs.balances(1)).mul(1e10); // WBTC, 8 decimals to 18 decimals uint256 _totalValueOfHBTCWBTC = _calcTotalValueOfLiquidityPool(_amountACurve, _wbtcPrice, _amountBCurve, _wbtcPrice); uint256 _clpTokenPriceHBTC = _calcValueOf1LPToken(_totalValueOfHBTCWBTC, clpToken.totalSupply()); // Pickle WBTC/ETH uint256 _pSlpTokenPriceWBTC = _calcPslpTokenPrice(pickleJarWBTC, slpWBTC, _wbtcPrice); // Sushiswap DPI/ETH uint256 _slpTokenPriceDPI = _calcSlpTokenPrice(slpDPI, _dpiPrice); // Pickle DAI/ETH uint256 _pSlpTokenPriceDAI = _calcPslpTokenPrice(pickleJarDAI, slpDAI, _daiPrice); return (_clpTokenPriceHBTC, _pSlpTokenPriceWBTC, _slpTokenPriceDPI, _pSlpTokenPriceDAI); } /// @notice Function to calculate price of Pickle LP token /// @param _pslpToken Type of Pickle SLP token /// @param _slpToken Type of SushiSwap LP token /// @param _tokenAPrice Price of SushiSwap LP token /// @return Price of Pickle LP token in ETH function _calcPslpTokenPrice(IPickleJar _pslpToken, ISLPToken _slpToken, uint256 _tokenAPrice) private view returns (uint256) { uint256 _slpTokenPrice = _calcSlpTokenPrice(_slpToken, _tokenAPrice); uint256 _totalValueOfPSlpToken = _calcTotalValueOfLiquidityPool(_pslpToken.balance(), _slpTokenPrice, 0, 0); return _calcValueOf1LPToken(_totalValueOfPSlpToken, _pslpToken.totalSupply()); } /// @notice Function to calculate price of SushiSwap LP Token /// @param _slpToken Type of SushiSwap LP token /// @param _tokenAPrice Price of SushiSwap LP token /// @return Price of SushiSwap LP Token in ETH function _calcSlpTokenPrice(ISLPToken _slpToken, uint256 _tokenAPrice) private view returns (uint256) { (uint112 _reserveA, uint112 _reserveB,) = _slpToken.getReserves(); if (_slpToken == slpWBTC) { // Change WBTC to 18 decimals _reserveA * 1e10; } uint256 _totalValueOfLiquidityPool = _calcTotalValueOfLiquidityPool(uint256(_reserveA), _tokenAPrice, uint256(_reserveB), 1e18); return _calcValueOf1LPToken(_totalValueOfLiquidityPool, _slpToken.totalSupply()); } /// @notice Calculate total value of liquidity pool /// @param _amountA Amount of one side of reserves /// @param _priceA Price of one side of reserves /// @param _amountB Amount of another side of reserves (if available) /// @param _priceB Price of another side of reserves (if available) /// @return Total value of liquidity pool (18 decimals) function _calcTotalValueOfLiquidityPool(uint256 _amountA, uint256 _priceA, uint256 _amountB, uint256 _priceB) private pure returns (uint256) { return (_amountA.mul(_priceA)).add(_amountB.mul(_priceB)); } /// @notice Function to calculate price of 1 LP Token /// @param _totalValueOfLiquidityPool Amount from _calcTotalValueOfLiquidityPool() /// @param _circulatingSupplyOfLPTokens totalSupply() of LP token /// @return Price of 1 LP Token (18 decimals) function _calcValueOf1LPToken(uint256 _totalValueOfLiquidityPool, uint256 _circulatingSupplyOfLPTokens) private pure returns (uint256) { return _totalValueOfLiquidityPool.div(_circulatingSupplyOfLPTokens); } /// @notice Function to get token price(only for DPI and DAI in this contract) /// @param _priceFeedProxy Address of ChainLink contract that provide oracle price /// @return Price in ETH function _getTokenPriceFromChainlink(address _priceFeedProxy) private view returns (uint256) { IChainlink _pricefeed = IChainlink(_priceFeedProxy); int256 _price = _pricefeed.latestAnswer(); return uint256(_price); } /// @notice Get current pool(sum of 4 pools with latest price updated) /// @return Current pool in ETH function getCurrentPool() public view returns (uint256) { if (!isVesting) { (uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice(); uint256 poolHBTCWBTC = _poolHBTCWBTC.mul(_clpTokenPriceHBTC).div(_HBTCWBTCLPTokenPrice); uint256 poolWBTCETH = _poolWBTCETH.mul(_pSlpTokenPriceWBTC).div(_WBTCETHLPTokenPrice); uint256 poolDPIETH = _poolDPIETH.mul(_slpTokenPriceDPI).div(_DPIETHLPTokenPrice); uint256 poolDAIETH = _poolDAIETH.mul(_pSlpTokenPriceDAI).div(_DAIETHLPTokenPrice); return poolHBTCWBTC.add(poolWBTCETH).add(poolDPIETH).add(poolDAIETH); } else { return _pool; } } /// @notice Get total pool(sum of 4 pools) /// @return Total pool in ETH function _getTotalPool() private view returns (uint256) { if (!isVesting) { return _poolHBTCWBTC.add(_poolWBTCETH).add(_poolDPIETH).add(_poolDAIETH); } else { return _pool; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT 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.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; } }
@notice Function to unstake LP token from Pickle Farm(gaugeP_WBTC), @notice withdraw from Pickle Jar(pickleJarWBTC), @notice and remove liquidity(router) from SushiSwap @param _amount Amount to withdraw in ETH
function _withdrawPickleWBTC(uint256 _amount) private { uint256 _totalPlpToken = gaugeP_WBTC.balanceOf(address(this)); uint256 _plpTokenShare = _totalPlpToken.mul(_amount).div(_poolWBTCETH); gaugeP_WBTC.withdraw(_plpTokenShare); pickleJarWBTC.withdraw(_plpTokenShare); router.removeLiquidity(address(WBTC), address(WETH), slpWBTC.balanceOf(address(this)), 0, 0, address(this), block.timestamp); _poolWBTCETH = _poolWBTCETH.sub(_amount); }
13,496,275
[ 1, 2083, 358, 640, 334, 911, 511, 52, 1147, 628, 23038, 298, 478, 4610, 12, 75, 8305, 52, 67, 59, 38, 15988, 3631, 225, 598, 9446, 628, 23038, 298, 15644, 12, 20847, 10813, 59, 38, 15988, 3631, 225, 471, 1206, 4501, 372, 24237, 12, 10717, 13, 628, 348, 1218, 77, 12521, 225, 389, 8949, 16811, 358, 598, 9446, 316, 512, 2455, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1918, 9446, 17968, 298, 59, 38, 15988, 12, 11890, 5034, 389, 8949, 13, 3238, 288, 203, 3639, 2254, 5034, 389, 4963, 1749, 84, 1345, 273, 13335, 52, 67, 59, 38, 15988, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 389, 412, 84, 1345, 9535, 273, 389, 4963, 1749, 84, 1345, 18, 16411, 24899, 8949, 2934, 2892, 24899, 6011, 59, 38, 56, 1441, 2455, 1769, 203, 3639, 13335, 52, 67, 59, 38, 15988, 18, 1918, 9446, 24899, 412, 84, 1345, 9535, 1769, 203, 3639, 13379, 10813, 59, 38, 15988, 18, 1918, 9446, 24899, 412, 84, 1345, 9535, 1769, 203, 3639, 4633, 18, 4479, 48, 18988, 24237, 12, 2867, 12, 59, 38, 15988, 3631, 1758, 12, 59, 1584, 44, 3631, 2020, 84, 59, 38, 15988, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 374, 16, 374, 16, 1758, 12, 2211, 3631, 1203, 18, 5508, 1769, 203, 3639, 389, 6011, 59, 38, 56, 1441, 2455, 273, 389, 6011, 59, 38, 56, 1441, 2455, 18, 1717, 24899, 8949, 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 ]
pragma solidity 0.5.16; /** * @title FundRaiser Smart Contract * @author Malarena SA - www.malarena.com * @notice A Fund Raising Smart Contract used to raise funds, with payments then released based on contributors voting */ contract FundRaiser { using SafeMath for uint256; // Initial set-up of Struct for Spending Requests struct Request { string description; uint256 value; address payable recipient; bool completed; uint256 numberOfVoters; mapping(address => bool) voters; } // Initial storage variables uint256 public deadline; // Deadline Block Number for fundraising campaign uint256 public initialPaymentDeadline; // Deadline Block Number for initial payment release to be approved and processed uint256 public goal; // Total amount needing to be raised, in wei uint256 public minimumContribution; // Minimum contribution value, in wei address public owner; // Ethereum address of the Smart Contract owner uint256 public totalContributors; // Total number of contributors uint256 public totalRequests; // Total number of spending requests uint256 public amountRaised; // Total amount actually raised uint256 public amountPaidOut; // Total amount actually paid out uint256 public requestCountMax = 100; // Max Count of Spending Requests, required to stop refund/remove voting loop from getting out of gas. Recommend 100 and never > 1000 Request[] public requests; mapping(address => uint256) public contributions; event Contribution(address indexed from, uint256 value); // Confirmation of Contribution processed event Refund(address indexed to, uint256 value); // Confirmation of Refund processed event RequestCreated(address indexed from, uint256 requestId, string description, uint256 value, address recipient); // Confirmation of Spending Request Created event Vote(address indexed from, uint256 requestId); // Confirmation of Vote processed event PaymentReleased(address indexed from, uint256 requestId, uint256 value, address recipient); // Confirmation of Spending Request Payment Released event OwnerChanged(address indexed from, address to); // Confirmation of Owner change processed /** * @notice Constructor Function used to deploy contract * @dev During Deploy the Ethereum address used to deploy the Smart Contract is set as the "owner" and certain functions below can only be actioned by the owner * @param _duration Duration of fund-raising part of Contract, in blocks * @param _initialPaymentDuration Period after _duration for owner to start releasing payments, in blocks * @param _goal Financial goal of the Smart Contract, in wei * @param _minimumContribution Minimum amount required for each contribution, in wei */ constructor(uint256 _duration, uint256 _initialPaymentDuration, uint256 _goal, uint256 _minimumContribution) public { deadline = block.number + _duration; initialPaymentDeadline = block.number + _duration + _initialPaymentDuration; goal = _goal; minimumContribution = _minimumContribution; owner = msg.sender; } /** * @notice OnlyOwner Function Modifier * @dev Function Modifier used to restrict certain functions so that they can only be actioned by the contract owner */ modifier onlyOwner { require(msg.sender == owner, "Caller is not the contract owner"); _; } /** * @dev Fallback Function not allowed * @dev Removed as contracts without a fallback function now automatically revert payments */ /* function() external { revert("Fallback method not allowed"); } */ /** * @notice Change the owner of the contract * @dev Can only be actioned by the current owner. Requires that _newOwner is not address zero * @param _newOwner Address of new contract owner */ function changeOwner(address _newOwner) external onlyOwner returns (bool) { require(_newOwner != address(0), "Invalid Owner change to address zero"); owner = _newOwner; emit OwnerChanged(msg.sender, _newOwner); return true; } /** * @notice Process a Contribution * @dev Payable function that should be sent Ether. Requires that minimum contribution value is met and deadline is not passed */ function contribute() external payable returns (bool) { require(msg.value >= minimumContribution, "Minimum Contribution level not met"); require(block.number <= deadline, "Deadline is passed"); // Check if it is the first time the contributor is contributing if(contributions[msg.sender] == 0) { totalContributors = totalContributors.add(1); } contributions[msg.sender] = contributions[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); emit Contribution(msg.sender, msg.value); return true; } /** * @notice Process a Refund, including reversing any voting * @dev Requires that the contribution exists, the deadline has passed and NO payments have been made. If the goal is reached then requires that initialPaymentDeadline has passed */ function getRefund() external returns (bool) { require(contributions[msg.sender] > 0, "No contribution to return"); require(block.number > deadline, "Deadline not reached"); require(amountPaidOut == 0, "Payments have already been made"); if (amountRaised >= goal) { require(block.number > initialPaymentDeadline, "Initial Payment Deadline not reached"); } uint256 amountToRefund = contributions[msg.sender]; contributions[msg.sender] = 0; totalContributors = totalContributors.sub(1); // amountRaised = amountRaised.sub(amountToRefund); // Removed to allow createRequest to still work if fundRaiser passed goal but then had refunds for (uint x = 0; (x < totalRequests && x < requestCountMax); x++) { Request storage thisRequest = requests[x]; if (thisRequest.voters[msg.sender] == true) { thisRequest.voters[msg.sender] = false; thisRequest.numberOfVoters = thisRequest.numberOfVoters.sub(1); } } msg.sender.transfer(amountToRefund); emit Refund(msg.sender, amountToRefund); return true; } /** * @notice Create a spending request * @dev Can only be actioned by the owner. Requires that the goal has been reached and the _value is not zero and does not exceed amountRaised or balance available on the contract. Also requires that _recipient is not address zero and requestCountMax has not been reached. Each spending request is stored sequentially starting from record 0 * @param _description A description of what the money will be spent on * @param _value The amount being spent with this spending request * @param _recipient The Ethereum address of where the money will be sent */ function createRequest(string calldata _description, uint256 _value, address payable _recipient) external onlyOwner returns (bool) { require(_value > 0, "Spending request value cannot be zero"); require(amountRaised >= goal, "Amount Raised is less than Goal"); require(_value <= address(this).balance, "Spending request value greater than amount available"); require(_recipient != address(0), "Invalid Recipient of address zero"); require(totalRequests < requestCountMax, "Spending Request Count limit reached"); Request memory newRequest = Request({ description: _description, value: _value, recipient: _recipient, completed: false, numberOfVoters: 0 }); requests.push(newRequest); totalRequests = totalRequests.add(1); emit RequestCreated(msg.sender, totalRequests.sub(1), _description, _value, _recipient); return true; } /** * @notice Vote for a spending request * @dev Requires that the caller made a contribution and has not already voted for the request. Also requires that the request exists and is not completed * @param _index Index Number of Spending Request to vote for */ function voteForRequest(uint256 _index) external returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; require(thisRequest.completed == false, "Request already completed"); require(contributions[msg.sender] > 0, "No contribution from Caller"); require(thisRequest.voters[msg.sender] == false, "Caller already voted"); thisRequest.voters[msg.sender] = true; thisRequest.numberOfVoters = thisRequest.numberOfVoters.add(1); emit Vote(msg.sender, _index); return true; } /** * @notice View if account has voted for spending request * @dev Requires that the request exists * @param _index Index Number of Spending Request to check * @param _account Address of Account to check */ function hasVoted(uint256 _index, address _account) external view returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; return thisRequest.voters[_account]; } /** * @notice Release the payment for a spending request * @dev Can only be actioned by the owner. Requires that the request exists and is not completed, and that there are funds available to make the payment. Also requires that over 50% of the contributors voted for the request * @param _index Index Number of Spending Request to release payment */ function releasePayment(uint256 _index) external onlyOwner returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; require(thisRequest.completed == false, "Request already completed"); require(thisRequest.numberOfVoters > totalContributors / 2, "Less than a majority voted"); require(thisRequest.value <= address(this).balance, "Spending request value greater than amount available"); amountPaidOut = amountPaidOut.add(thisRequest.value); thisRequest.completed = true; thisRequest.recipient.transfer(thisRequest.value); emit PaymentReleased(msg.sender, _index, thisRequest.value, thisRequest.recipient); return true; } /** * @notice Test Functions * @dev These functions are ONLY required to expose the SafeMath internal Library functions and the changeRequestCountMax function for testing. These can be commented or removed after testing */ /* function testAdd(uint256 a, uint256 b) external pure returns (uint256) { return SafeMath.add(a, b); } function testSub(uint256 a, uint256 b) external pure returns (uint256) { return SafeMath.sub(a, b); } event RequestCountMaxChanged(uint256 value); function changeRequestCountMax(uint256 _newRequestCountMax) external onlyOwner returns (bool) { require(_newRequestCountMax > 0, "Request Count limit cannot be less than zero"); require(_newRequestCountMax >= totalRequests, "Request Count limit cannot be less than Total Current Requests"); requestCountMax = _newRequestCountMax; emit RequestCountMaxChanged( _newRequestCountMax); return true; } */ } /** * @notice SafeMath Library * @dev Based on OpenZeppelin/SafeMath Library * @dev Used to avoid Solidity Overflow Errors * @dev Only add and sub functions used in this contract - others removed */ library SafeMath { // Returns the addition of two unsigned integers & reverts on overflow function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } // Returns the subtraction of two unsigned integers & reverts on overflow function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } }
* @notice Process a Refund, including reversing any voting @dev Requires that the contribution exists, the deadline has passed and NO payments have been made. If the goal is reached then requires that initialPaymentDeadline has passed/ amountRaised = amountRaised.sub(amountToRefund); Removed to allow createRequest to still work if fundRaiser passed goal but then had refunds
function getRefund() external returns (bool) { require(contributions[msg.sender] > 0, "No contribution to return"); require(block.number > deadline, "Deadline not reached"); require(amountPaidOut == 0, "Payments have already been made"); if (amountRaised >= goal) { require(block.number > initialPaymentDeadline, "Initial Payment Deadline not reached"); } uint256 amountToRefund = contributions[msg.sender]; contributions[msg.sender] = 0; totalContributors = totalContributors.sub(1); for (uint x = 0; (x < totalRequests && x < requestCountMax); x++) { Request storage thisRequest = requests[x]; if (thisRequest.voters[msg.sender] == true) { thisRequest.voters[msg.sender] = false; thisRequest.numberOfVoters = thisRequest.numberOfVoters.sub(1); } } msg.sender.transfer(amountToRefund); emit Refund(msg.sender, amountToRefund); return true; }
12,880,400
[ 1, 2227, 279, 3941, 1074, 16, 6508, 19795, 310, 1281, 331, 17128, 225, 16412, 716, 326, 24880, 1704, 16, 326, 14096, 711, 2275, 471, 3741, 25754, 1240, 2118, 7165, 18, 971, 326, 17683, 353, 8675, 1508, 4991, 716, 2172, 6032, 15839, 711, 2275, 19, 3844, 12649, 5918, 273, 3844, 12649, 5918, 18, 1717, 12, 8949, 774, 21537, 1769, 225, 2663, 9952, 358, 1699, 15798, 358, 4859, 1440, 309, 284, 1074, 12649, 15914, 2275, 17683, 1496, 1508, 9323, 16255, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17404, 1074, 1435, 3903, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 591, 15326, 63, 3576, 18, 15330, 65, 405, 374, 16, 315, 2279, 24880, 358, 327, 8863, 203, 565, 2583, 12, 2629, 18, 2696, 405, 14096, 16, 315, 15839, 486, 8675, 8863, 203, 565, 2583, 12, 8949, 16507, 350, 1182, 422, 374, 16, 315, 23725, 1240, 1818, 2118, 7165, 8863, 203, 565, 309, 261, 8949, 12649, 5918, 1545, 17683, 13, 288, 203, 1377, 2583, 12, 2629, 18, 2696, 405, 2172, 6032, 15839, 16, 315, 4435, 12022, 23967, 1369, 486, 8675, 8863, 203, 565, 289, 203, 565, 2254, 5034, 3844, 774, 21537, 273, 13608, 6170, 63, 3576, 18, 15330, 15533, 203, 565, 13608, 6170, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 2078, 442, 665, 13595, 273, 2078, 442, 665, 13595, 18, 1717, 12, 21, 1769, 203, 565, 364, 261, 11890, 619, 273, 374, 31, 261, 92, 411, 2078, 6421, 597, 619, 411, 590, 1380, 2747, 1769, 619, 27245, 288, 203, 1377, 1567, 2502, 333, 691, 273, 3285, 63, 92, 15533, 203, 1377, 309, 261, 2211, 691, 18, 90, 352, 414, 63, 3576, 18, 15330, 65, 422, 638, 13, 288, 203, 3639, 333, 691, 18, 90, 352, 414, 63, 3576, 18, 15330, 65, 273, 629, 31, 203, 3639, 333, 691, 18, 2696, 951, 58, 352, 414, 273, 333, 691, 18, 2696, 951, 58, 352, 414, 18, 1717, 12, 21, 1769, 203, 1377, 289, 203, 565, 289, 203, 565, 1234, 18, 15330, 18, 13866, 12, 8949, 774, 21537, 1769, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./BokkyPooBahsDateTimeLibrary.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol"; contract VortexTokenVesting is Ownable { using SafeMath for uint256; using BokkyPooBahsDateTimeLibrary for uint256; using SafeERC20 for IERC20; event DistributionAdded(address indexed investor, address indexed caller, uint256 allocation); event DistributionRemoved(address indexed investor, address indexed caller, uint256 allocation); event WithdrawnTokens(address indexed investor, uint256 value); event RecoverToken(address indexed token, uint256 indexed amount); enum DistributionType { RESERVE, REWARDS, TEAM_ADVISORS } uint256 private _initialTimestamp; IERC20 private _vortexToken; struct Distribution { address beneficiary; uint256 withdrawnTokens; uint256 tokensAllotment; DistributionType distributionType; } mapping(DistributionType => Distribution) public distributionInfo; /// @dev Boolean variable that indicates whether the contract was initialized. bool public isInitialized = false; /// @dev Boolean variable that indicates whether the investors set was finalized. bool public isFinalized = false; address _tressuryAddresss = 0x68B6eEC457E8fdd4886F0A91BA7444eC7D6bfaB1; uint256 constant _SCALING_FACTOR = 10**18; // decimals uint256 constant _year = 365 days; uint256 _oneMonth = _year.div(12); uint256 _cliff = _oneMonth.mul(6); /// @dev Checks that the contract is initialized. modifier initialized() { require(isInitialized, "not initialized"); _; } /// @dev Checks that the contract is initialized. modifier notInitialized() { require(!isInitialized, "initialized"); _; } constructor(address _token) { require(address(_token) != address(0x0), "Vortex token address is not valid"); _vortexToken = IERC20(_token); _addDistribution(_tressuryAddresss, DistributionType.RESERVE, 8000000 * _SCALING_FACTOR); _addDistribution(_tressuryAddresss, DistributionType.REWARDS, 27000000 * _SCALING_FACTOR); _addDistribution(_tressuryAddresss, DistributionType.TEAM_ADVISORS, 20000000 * _SCALING_FACTOR); } /// @dev Returns initial timestamp function getInitialTimestamp() public view returns (uint256 timestamp) { return _initialTimestamp; } /// @dev Adds Distribution. This function doesn't limit max gas consumption, /// so adding too many investors can cause it to reach the out-of-gas error. /// @param _beneficiary The address of distribution. /// @param _tokensAllotment The amounts of the tokens that belong to each investor. function _addDistribution( address _beneficiary, DistributionType _distributionType, uint256 _tokensAllotment ) internal { require(_beneficiary != address(0), "Invalid address"); require(_tokensAllotment > 0, "the investor allocation must be more than 0"); Distribution storage distribution = distributionInfo[_distributionType]; require(distribution.tokensAllotment == 0, "investor already added"); distribution.beneficiary = _beneficiary; distribution.tokensAllotment = _tokensAllotment; distribution.distributionType = _distributionType; emit DistributionAdded(_beneficiary, _msgSender(), _tokensAllotment); } function withdrawTokens(uint256 _distributionType) external onlyOwner() initialized() { Distribution storage distribution = distributionInfo[DistributionType(_distributionType)]; uint256 tokensAvailable = withdrawableTokens(DistributionType(_distributionType)); require(tokensAvailable > 0, "no tokens available for withdrawl"); distribution.withdrawnTokens = distribution.withdrawnTokens.add(tokensAvailable); _vortexToken.safeTransfer(distribution.beneficiary, tokensAvailable); emit WithdrawnTokens(_msgSender(), tokensAvailable); } /// @dev The starting time of TGE /// @param _timestamp The initial timestamp, this timestap should be used for vesting function setInitialTimestamp(uint256 _timestamp) external onlyOwner() notInitialized() { isInitialized = true; _initialTimestamp = _timestamp; } function withdrawableTokens(DistributionType distributionType) public view returns (uint256 tokens) { Distribution storage distribution = distributionInfo[distributionType]; uint256 availablePercentage = _calculateAvailablePercentage(distributionType); // console.log("Available Percentage: %s", availablePercentage); uint256 noOfTokens = _calculatePercentage(distribution.tokensAllotment, availablePercentage); uint256 tokensAvailable = noOfTokens.sub(distribution.withdrawnTokens); // console.log("Withdrawable Tokens: %s", tokensAvailable); return tokensAvailable; } function _calculatePercentage(uint256 _amount, uint256 _percentage) private pure returns (uint256 percentage) { return _amount.mul(_percentage).div(100).div(1e18); } function _getCommunityRewardsPercentage(uint256 _currentTimeStamp) private view returns (uint256 _availablePercentage) { // Unlocked 16.66% every 6 months starting from TGE uint256 sixMonths = _initialTimestamp + _oneMonth * 6; uint256 oneYear = _initialTimestamp + 365 days; uint256 eighteenMonths = _initialTimestamp + _oneMonth * 18; uint256 twentyFourMonths = _initialTimestamp + _oneMonth * 24; uint256 thirtyMonths = _initialTimestamp + _oneMonth * 30; // console.log("Current TimeStamp %s %s", _currentTimeStamp ,_currentTimeStamp <= sixMonths); // console.log(_currentTimeStamp > sixMonths && _currentTimeStamp < oneYear); // console.log(_currentTimeStamp > eighteenMonths && _currentTimeStamp < twentyFourMonths); if (_currentTimeStamp <= sixMonths) { return 16600000000000000000; } else if (_currentTimeStamp > sixMonths && _currentTimeStamp < oneYear) { return 33200000000000000000; } else if (_currentTimeStamp > oneYear && _currentTimeStamp < eighteenMonths) { return 49800000000000000000; } else if (_currentTimeStamp > eighteenMonths && _currentTimeStamp < twentyFourMonths) { return 66400000000000000000; } else if (_currentTimeStamp > twentyFourMonths && _currentTimeStamp < thirtyMonths) { return 83000000000000000000; } else { return uint256(100).mul(1e18); } } function _getAdvisorsPercentage(uint256 _currentTimeStamp) private view returns (uint256 _availablePercentage) { // TEAM 150 Days Lock from TGE, Released daily over 365 Days after 150 days cliff uint256 cliffDuration = _initialTimestamp + 150 days; uint256 duration = _initialTimestamp + 365 days + 150 days; uint256 remainingDistroPercentage = 100; uint256 noOfRemaingDays = 365; uint256 everyDayReleasePercentage = remainingDistroPercentage.mul(1e18).div(noOfRemaingDays); //0.273972603% // console.log("Every Day Relase: %s", everyDayReleasePercentage); if (_currentTimeStamp > cliffDuration) { // Date difference in days - (endDate - startDate) / 60 / 60 / 24; // 40 days if(_currentTimeStamp < duration) { uint256 noOfDays = BokkyPooBahsDateTimeLibrary.diffDays(cliffDuration, _currentTimeStamp); // console.log("Number of days: %s", noOfDays); uint256 currentUnlockedPercentage = noOfDays.mul(1e18).mul(everyDayReleasePercentage).div(1e18); // console.log("Current Unlock: %s", currentUnlockedPercentage); return currentUnlockedPercentage; } else { return uint256(100).mul(1e18); } } else { return uint256(0); } } function _calculateAvailablePercentage(DistributionType distributionType) private view returns (uint256 _availablePercentage) { uint256 currentTimeStamp = block.timestamp; if (currentTimeStamp > _initialTimestamp) { if (distributionType == DistributionType.RESERVE) { // RESERVE Locked for 1 year from TGE if (currentTimeStamp <= _initialTimestamp + _year) { return uint256(0).mul(1e18); } else if (currentTimeStamp > _initialTimestamp + _year) { return uint256(100).mul(1e18); } } else if (distributionType == DistributionType.REWARDS) { return _getCommunityRewardsPercentage(currentTimeStamp); } else if (distributionType == DistributionType.TEAM_ADVISORS) { return _getAdvisorsPercentage(currentTimeStamp); } } } function recoverExcessToken(address _token, uint256 amount) external onlyOwner { IERC20(_token).safeTransfer(_msgSender(), amount); emit RecoverToken(_token, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // 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.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); } } } }
------------------------------------------------------------------------ Calculate the number of days from 1970/01/01 to year/month/day using the date conversion algorithm from http:aa.usno.navy.mil/faq/docs/JD_Formula.php and subtracting the offset 2440588 so that 1970/01/01 is day 0 days = day - 32075 + 1461 * (year + 4800 + (month - 14) / 12) / 4 + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 - offset ------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; daysInMonth = 30; daysInMonth = _isLeapYear(year) ? 29 : 28; } } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; daysInMonth = 30; daysInMonth = _isLeapYear(year) ? 29 : 28; } } } else if (month != 2) { } else { function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
419,999
[ 1, 29461, 9029, 326, 1300, 434, 4681, 628, 5342, 7301, 19, 1611, 19, 1611, 358, 3286, 19, 7496, 19, 2881, 1450, 326, 1509, 4105, 4886, 628, 282, 1062, 30, 7598, 18, 407, 2135, 18, 11589, 93, 18, 81, 330, 19, 507, 85, 19, 8532, 19, 46, 40, 67, 14972, 18, 2684, 471, 10418, 310, 326, 1384, 4248, 24, 6260, 5482, 1427, 716, 5342, 7301, 19, 1611, 19, 1611, 353, 2548, 374, 4681, 273, 2548, 1377, 300, 890, 3462, 5877, 1377, 397, 5045, 9498, 225, 261, 6874, 397, 9934, 713, 397, 261, 7496, 300, 5045, 13, 342, 2593, 13, 342, 1059, 1377, 397, 6580, 27, 225, 261, 7496, 300, 576, 300, 261, 7496, 300, 5045, 13, 342, 2593, 225, 2593, 13, 342, 2593, 1377, 300, 890, 225, 14015, 6874, 397, 17160, 713, 397, 261, 7496, 300, 5045, 13, 342, 2593, 13, 342, 2130, 13, 342, 1059, 1377, 300, 1384, 8879, 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, 12083, 605, 601, 18465, 52, 5161, 38, 69, 4487, 5096, 9313, 288, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 10339, 273, 4248, 380, 4752, 380, 4752, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 21372, 273, 4752, 380, 4752, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 30090, 273, 4752, 31, 203, 565, 509, 5034, 5381, 26019, 31728, 11664, 1611, 273, 4248, 24, 6260, 5482, 31, 203, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 17667, 273, 404, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 56, 1821, 273, 576, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 59, 2056, 273, 890, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 2455, 57, 273, 1059, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 42, 2259, 273, 1381, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 55, 789, 273, 1666, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 55, 2124, 273, 2371, 31, 203, 203, 565, 445, 389, 9810, 1265, 1626, 12, 203, 3639, 2254, 5034, 3286, 16, 203, 3639, 2254, 5034, 3138, 16, 203, 3639, 2254, 5034, 2548, 203, 203, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 389, 9810, 13, 288, 203, 3639, 2583, 12, 6874, 1545, 5342, 7301, 1769, 203, 3639, 509, 5034, 389, 6874, 273, 509, 5034, 12, 6874, 1769, 203, 3639, 509, 5034, 389, 7496, 273, 509, 5034, 12, 7496, 1769, 203, 3639, 509, 5034, 389, 2881, 273, 509, 5034, 12, 2881, 1769, 203, 203, 3639, 509, 5034, 2 ]
pragma solidity ^0.5.0; //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 minimum value in an array. */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { max = data[1]; maxIndex; for (uint256 i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an 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 - 1; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } } /** * @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; /*Functions*/ /*Tellor Getters*/ /** * @dev This function gets the 5 miners currently selected for providing data * @return miners an array of the miner addresses */ function getCurrentMiners(TellorStorage.TellorStorageStruct storage self) internal view returns(address[] memory miners){ return self.selectedValidators; } /** * @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) internal 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")] */ 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 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, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.reportedMiner, disp.reportingParty, [ 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, currentRequestId, 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) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], 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 getDisputeIdsByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256[] memory) { return self.disputeIdsByDisputeHash[_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 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 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 (uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _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 * @return uint stakePosition for the staker */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256,uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate, self.stakerDetails[_staker].stakePosition.length); } /** * @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 */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } /** * @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 look up * @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]; } } /** * @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; //emits when a tip is added to a requestId 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 indexed _currentRequestId, uint256 _totalTips ); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewRequestOnDeck(uint256 indexed _requestId, uint256 _onDeckTotalTips); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge); //Emits upon each mine (5 total) and shows the miner, and value submitted event SolutionSubmitted(address indexed _miner, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge); //emits when a new validator is selected event NewValidatorsSelected(address _validator); /*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"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.allowance(msg.sender,address(this)) >= _tip,"Allowance must be set"); //If the tip > 0 transfer the tip to this contract require (_tip >= 5, "Tip must be greater than 5");//must be greater than 5 loyas so each miner gets at least 1 loya tellorToken.transferFrom(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[keccak256("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 _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; //The sorting algorithm that sorts the values of the first five values that come in TellorStorage.Details[5] memory a = self.currentMiners; uint256 i; for (i = 1; i < 5; i++) { uint256 temp = a[i].value; address temp2 = a[i].miner; uint256 j = i; while (j > 0 && temp < a[j - 1].value) { a[j].value = a[j - 1].value; a[j].miner = a[j - 1].miner; j--; } if (j < i) { a[j].value = temp; a[j].miner = temp2; } } //Pay the miners for (i = 0; i < 5; i++) { tellorToken.transfer(a[i].miner, self.uintVars[keccak256("currentTotalTips")] / 5); } emit NewValue( _requestId, _timeOfLastNewValue, a[2].value, self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5), self.currentChallenge ); //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2].value; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); //re-start the count for the slot progress to zero before the new request mining starts self.uintVars[keccak256("slotProgress")] = 0; uint256 _topId = TellorGettersLibrary.getTopRequestID(self); self.uintVars[keccak256("currentRequestId")] = _topId; //if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout //else wait for a new tip to mine if (_topId > 0) { selectNewValidators(self,true); self.currentChallenge = keccak256(abi.encodePacked(randomnumber(self,_timeOfLastNewValue,a[2].value), self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof //Update the current request to be mined to the requestID with the highest payout self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")]; //Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0; //Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next //and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0; //gets the max tip in the in the requestQ[51] array and its index within the array?? uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self); //Issue the the next requestID emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("currentTotalTips")] ); emit NewRequestOnDeck( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } else { self.uintVars[keccak256("currentTotalTips")] = 0; self.currentChallenge = ""; self.selectedValidators.length = 0; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _value) public { //requre miner is staked require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); //Check the miner is submitting the pow for the current request Id require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong"); //Check the validator submitting data is one of the selected validators require(self.validValidator[msg.sender] == true, "Not a selected validator"); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //Save the miner and value received self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value; self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender; //Add to the count how many values have been submitted, since only 5 are taken per request self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit SolutionSubmitted(msg.sender, _requestId, _value, self.currentChallenge); //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received //Once a validator submits data set their status back to false self.validValidator[msg.sender] = false; if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _requestId); } } /** * @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) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self); _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); //Set _payout for the submitted request uint256 _payout = _request.apiUintVars[keccak256("totalTip")]; //If there is no current request being mined //then set the currentRequestId to the requestid of the requestData or addtip requestId submitted, // the totalTips to the payout/tip submitted, and issue a new mining challenge if (self.uintVars[keccak256("currentRequestId")] == 0) { self.uintVars[keccak256("currentRequestId")] = _requestId; self.uintVars[keccak256("currentTotalTips")] = _payout; self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof selectNewValidators(self,true); emit NewChallenge( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("currentTotalTips")] ); } else if (_requestId == self.uintVars[keccak256("currentRequestId")]) { self.uintVars[keccak256("currentTotalTips")] = self.uintVars[keccak256("currentTotalTips")] + _payout; }else { //If there is no OnDeckRequestId //then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what //is being currently mined) if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")]) { //let everyone know the next on queue has been replaced emit NewRequestOnDeck(_requestId, _payout); } //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[keccak256("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 (_payout > _min) { self.requestQ[_index] = _payout; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] = _payout; } } } /** * @dev Reselects validators if any of the first five fail to submit data */ function reselectNewValidators(TellorStorage.TellorStorageStruct storage self) public{ require( self.uintVars[keccak256("lastSelection")] < now - 30, "has not been long enough reselect"); selectNewValidators(self,false);// ??? Does false mean to select new validators? } /** * @dev Generates a random number to select validators */ function randomnumber(TellorStorage.TellorStorageStruct storage self, uint _max, uint _nonce) internal view returns (uint){ return uint(keccak256(abi.encodePacked(_nonce,now,self.uintVars[keccak256("totalTip")],msg.sender,block.difficulty,self.stakers.length))) % _max; } /** * @dev Selects validators * @param _reset true to delete existing validators and re-selected */ function selectNewValidators(TellorStorage.TellorStorageStruct storage self, bool _reset) public{ if(_reset){ self.selectedValidators.length = 0; } uint j=0; uint i=0; uint r; address potentialValidator; while(j < 5 && self.stakers.length > self.selectedValidators.length){ i++; r = randomnumber(self,self.stakers.length,i); potentialValidator = self.stakers[r]; if(!self.validValidator[potentialValidator]){ self.selectedValidators.push(potentialValidator); emit NewValidatorsSelected(potentialValidator); self.validValidator[potentialValidator] = true;//used to check if they are a selectedvalidator (better than looping through array) j++; } } self.uintVars[keccak256("lastSelected")] = now; } } //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); } } } /** * @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? 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 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("quorum"); //quorum for dispute vote NEW // 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 uint256 startDate; //stake start date uint256 withdrawDate; uint256 withdrawAmount; uint[] stakePosition; mapping(uint => uint) stakePositionArrayIndex; } //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 { 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("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 { address[] selectedValidators; address[] stakers; mapping(address => uint) missedCalls;//if your missed calls gets up to 3, you lose a TRB. A successful retrieval resets its mapping(address => bool) validValidator; //ensures only selected validators can sumbmit data 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("_deity");//Tellor Owner that can do things at will 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("minimumPayment") //The minimum payment in TRB for a data request // keccak256("uniqueStakers")//Number of unique stakers // keccak256("lastSelected") //Time we last selected validators //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[]) disputeIdsByDisputeHash; //maps a hash to an ID for each dispute } } /** * @title Tellor Transfer * @dev Contais 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; /*Functions*/ /** * @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 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) internal { require(_amount > 0, "Tried to send non-positive amount"); uint256 previousBalance; if(_from != address(this)){ require(balanceOf(self, _from).sub(_amount) >= 0, "Stake amount was not removed from balance"); previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); } previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); } /** * @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) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /** * @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)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } /** * 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, uint _amount) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; require(stakes.currentStatus == 1, "Miner is not staked"); require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake"); require(_amount <= TellorTransfer.balanceOf(self,msg.sender)); for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++) { removeFromStakerArray(self, stakes.stakePosition[i],msg.sender); } //Change the miner staked to locked to be withdrawStake if (TellorTransfer.balanceOf(self,msg.sender) - _amount == 0){ stakes.currentStatus = 2; } stakes.withdrawDate = now - (now % 86400); stakes.withdrawAmount = _amount; 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.withdrawDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus !=3 , "Miner is under dispute"); TellorTransfer.doTransfer(self,msg.sender,address(0),stakes.withdrawAmount); if (TellorTransfer.balanceOf(self,msg.sender) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("stakerCount")] -= 1; self.uintVars[keccak256("uniqueStakers")] -= 1; } self.uintVars[keccak256("totalStaked")] -= stakes.withdrawAmount; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); tellorToken.transfer(msg.sender,stakes.withdrawAmount); emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake * @param _amount is the amount to be staked */ function depositStake(TellorStorage.TellorStorageStruct storage self, uint _amount) public { TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.allowance(msg.sender,address(this)) >= _amount, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _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[msg.sender].currentStatus == 0 || self.stakerDetails[msg.sender].currentStatus == 1, "Miner is in the wrong state"); //if this is the first time this addres stakes count, then add them to the stake count if(TellorTransfer.balanceOf(self,msg.sender) == 0){ self.uintVars[keccak256("uniqueStakers")] += 1; } require(_amount >= self.uintVars[keccak256("minimumStake")], "You must stake a certain amount"); require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake"); for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++){ self.stakerDetails[msg.sender].stakePosition.push(self.stakers.length); //self.stakerDetails[msg.sender].stakePositionArrayIndex[self.stakerDetails[msg.sender].stakerPosition.length] = self.stakers.length; self.stakers.push(msg.sender); self.uintVars[keccak256("stakerCount")] += 1; } self.stakerDetails[msg.sender].currentStatus = 1; self.stakerDetails[msg.sender].startDate = now - (now % 86400); TellorTransfer.doTransfer(self,address(this),msg.sender,_amount); self.uintVars[keccak256("totalStaked")] += _amount; emit NewStake(msg.sender); } /** * @dev This function is used by requestStakingWithdraw to remove the staker from the stakers array * @param _pos is the staker's position in the array * @param _staker is the staker's address */ function removeFromStakerArray(TellorStorage.TellorStorageStruct storage self, uint _pos, address _staker) internal{ address lastAdd; if(_pos == self.stakers.length-1){ self.stakers.length--; self.stakerDetails[_staker].stakePosition.length--; } else{ lastAdd = self.stakers[self.stakers.length-1]; self.stakers[_pos] = lastAdd; self.stakers.length--; self.stakerDetails[_staker].stakePosition.length--; } } } interface TokenInterface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function balanceOfAt(address tokenOwner, uint256 blockNumber) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /** * @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); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); /*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 that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" //require(now - _timestamp <= 1 days, "The value was mined more than a day ago"); 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)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint256 disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId uint256 _fee = self.uintVars[keccak256("disputeFee")] * 2**self.disputeIdsByDisputeHash[_hash].length; self.disputeIdsByDisputeHash[_hash].push(disputeId); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputesById[self.disputeIdsByDisputeHash[_hash][0]].disputeUintVars[keccak256("minExecutionDate")] < now, "Dispute is already open"); //Transfer dispute fee TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, 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 * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _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 //if they are staked weigh vote based on their staked + unstaked balance of TRB on the side chain uint256 voteWeight; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]) + tellorToken.balanceOfAt(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 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); } /** * @dev tallies the votes. * @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(disp.reportingParty != address(0)); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't 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 (disp.tally > 0) { //Set the dispute state to passed/true disp.disputeVotePassed = true; } if (stakes.currentStatus == 3){ stakes.currentStatus = 4; } //update the dispute status to executed disp.executed = true; disp.disputeUintVars[keccak256("tallyDate")] = now; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Unlocks the dispute fee * @param _disputeId is the dispute id */ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ //if reported miner stake has not been slashed yet, slash them and return the fee to reporting party if (stakes.currentStatus == 4) { //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); //Decreases the stakerCount since the miner's stake is being slashed TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; }else{ stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } //if reported miner stake was already slashed, return the fee to other reporting paties } else { for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ 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")]; } //tranfer the dispute fee to the miner if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } } /** * @title Tellor Getters * @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract * is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake */ contract TellorGetters { using SafeMath for uint256; using TellorTransfer for TellorStorage.TellorStorageStruct; using TellorGettersLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /** * @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(bytes32 _challenge, address _miner) external view returns (bool) { return tellor.didMine(_challenge, _miner); } /** * @dev This function gets the balance of the specified user address * @param _user is the address to check the balance for */ function balanceOf(address _user) external view returns(uint256){ return tellor.balanceOf(_user); } /** * @dev This function gets the currently selected validators * @return an array of the currently selected validators */ function getCurrentMiners() external view returns(address[] memory miners){ return tellor.getCurrentMiners(); } /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool) { return tellor.didVote(_disputeId, _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")] */ function getAddressVars(bytes32 _data) external view returns (address) { return tellor.getAddressVars(_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 address of reportedMiner * @return address of reportingParty * @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(uint256 _disputeId) public view returns (bytes32, bool, bool, address, address, uint256[9] memory, int256) { return tellor.getAllDisputeVars(_disputeId); } /** * @dev Getter function for variables for the requestId validators are currently providing data for * @return current challenge, curretnRequestId, total tip for the request */ function getCurrentVariables() external view returns (bytes32, uint256, uint256) { return tellor.getCurrentVariables(); } /** * @dev Checks if a given hash of validator,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint array of disputeIds */ function getDisputeIdsByDisputeHash(bytes32 _hash) external view returns (uint256[] memory) { return tellor.getDisputeIdsByDisputeHash(_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(uint256 _disputeId, bytes32 _data) external view returns (uint256) { return tellor.getDisputeUintVars(_disputeId, _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() external view returns (uint256, bool) { return tellor.getLastNewValue(); } /** * @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(uint256 _requestId) external view returns (uint256, bool) { return tellor.getLastNewValueById(_requestId); } /** * @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(uint256 _requestId, uint256 _timestamp) external view returns (uint256) { return tellor.getMinedBlockNum(_requestId, _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(uint256 _requestId, uint256 _timestamp) external view returns (address[5] memory) { return tellor.getMinersByRequestIdAndTimestamp(_requestId, _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(uint256 _requestId) external view returns (uint256) { return tellor.getNewValueCountbyRequestId(_requestId); } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256) { return tellor.getRequestIdByRequestQIndex(_index); } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256) { return tellor.getRequestIdByTimestamp(_timestamp); } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() public view returns (uint256[51] memory) { return tellor.getRequestQ(); } /** * @dev Allows 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(uint256 _requestId, bytes32 _data) external view returns (uint256) { return tellor.getRequestUintVars(_requestId, _data); } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns (uint256, uint256) { return tellor.getRequestVars(_requestId); } /** * @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 * @return uint stakePosition for the staker */ function getStakerInfo(address _staker) external view returns (uint256, uint256,uint256) { return tellor.getStakerInfo(_staker); } /** * @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(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory) { return tellor.getSubmissionsByTimestamp(_requestId, _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(uint256 _requestID, uint256 _index) external view returns (uint256) { return tellor.getTimestampbyRequestIDandIndex(_requestID, _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(bytes32 _data) public view returns (uint256) { return tellor.getUintVar(_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 */ function getVariablesOnDeck() external view returns (uint256, uint256) { return tellor.getVariablesOnDeck(); } /** * @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 bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool) { return tellor.isInDispute(_requestId, _timestamp); } /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256) { return tellor.retrieveData(_requestId, _timestamp); } } /** * @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 is TellorGetters{ using SafeMath for uint256; event NewTellorToken(address _token); /*Functions*/ constructor (address _tellorToken) public { tellor.uintVars[keccak256("decimals")] = 18; tellor.uintVars[keccak256("disputeFee")] = 10e18; tellor.uintVars[keccak256("minimumStake")] = 100e18; tellor.addressVars[keccak256("tellorToken")] = _tellorToken; emit NewTellorToken(_tellorToken); } /** * @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 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 Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(uint256 _requestId, uint256 _value) external { tellor.submitMiningSolution(_requestId, _value); } /** * @dev This function allows miners to deposit their stake. * @param _amount is the amount the sender wants to stake */ function depositStake(uint _amount) external { tellor.depositStake(_amount); } /** * @dev This function reselects validators if the originals did not complete the block */ function reselectNewValidators() external{ tellor.reselectNewValidators(); } /** * @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 * @param _amount to unstake */ function requestStakingWithdraw(uint _amount) external { tellor.requestStakingWithdraw(_amount); } /** * @dev This function allows for the dispute fee to be unlocked after the dispute vote has elapsed * @param _disputeId is the disputeId to unlock the fee from */ function unlockDisputeFee (uint _disputeId) external{ tellor.unlockDisputeFee(_disputeId); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @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; } }
emitted when a new dispute is initializedemitted when a new vote happensemitted upon dispute tally
library TellorDispute { using SafeMath for uint256; using SafeMath for int256; event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter); event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); 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"); address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } self.disputeIdsByDisputeHash[_hash].push(disputeId); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, executed: false, disputeVotePassed: false, tally: 0 }); 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 * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } 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"); address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } self.disputeIdsByDisputeHash[_hash].push(disputeId); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, executed: false, disputeVotePassed: false, tally: 0 }); 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 * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; uint256 _fee = self.uintVars[keccak256("disputeFee")] * 2**self.disputeIdsByDisputeHash[_hash].length; require(self.disputesById[self.disputeIdsByDisputeHash[_hash][0]].disputeUintVars[keccak256("minExecutionDate")] < now, "Dispute is already open"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); 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"); address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } self.disputeIdsByDisputeHash[_hash].push(disputeId); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, executed: false, disputeVotePassed: false, tally: 0 }); 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 * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; 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"); address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } self.disputeIdsByDisputeHash[_hash].push(disputeId); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, executed: false, disputeVotePassed: false, tally: 0 }); 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 * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; uint256 voteWeight; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]) + tellorToken.balanceOfAt(msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); require(disp.voted[msg.sender] != true, "Sender has already voted"); require(voteWeight > 0, "User balance is 0"); require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); disp.voted[msg.sender] = true; disp.disputeUintVars[keccak256("numberOfVotes")] += 1; if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); disp.tally = disp.tally.sub(int256(voteWeight)); } } function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; uint256 voteWeight; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]) + tellorToken.balanceOfAt(msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); require(disp.voted[msg.sender] != true, "Sender has already voted"); require(voteWeight > 0, "User balance is 0"); require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); disp.voted[msg.sender] = true; disp.disputeUintVars[keccak256("numberOfVotes")] += 1; if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); disp.tally = disp.tally.sub(int256(voteWeight)); } } } else { emit Voted(_disputeId, _supportsDispute, msg.sender); function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; require(disp.executed == false, "Dispute has been already executed"); require(disp.reportingParty != address(0)); require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; if (disp.tally > 0) { disp.disputeVotePassed = true; } if (stakes.currentStatus == 3){ stakes.currentStatus = 4; } disp.disputeUintVars[keccak256("tallyDate")] = now; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; require(disp.executed == false, "Dispute has been already executed"); require(disp.reportingParty != address(0)); require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; if (disp.tally > 0) { disp.disputeVotePassed = true; } if (stakes.currentStatus == 3){ stakes.currentStatus = 4; } disp.disputeUintVars[keccak256("tallyDate")] = now; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; require(disp.executed == false, "Dispute has been already executed"); require(disp.reportingParty != address(0)); require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; if (disp.tally > 0) { disp.disputeVotePassed = true; } if (stakes.currentStatus == 3){ stakes.currentStatus = 4; } disp.disputeUintVars[keccak256("tallyDate")] = now; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } disp.executed = true; function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } }else{ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } } else { function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ if (stakes.currentStatus == 4) { self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { _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 = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } }
12,579,083
[ 1, 351, 11541, 1347, 279, 394, 1015, 2507, 353, 4046, 323, 7948, 1347, 279, 394, 12501, 5865, 307, 7948, 12318, 1015, 2507, 268, 1230, 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, 12083, 29860, 280, 1669, 2507, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 509, 5034, 31, 203, 203, 565, 871, 1166, 1669, 2507, 12, 11890, 5034, 8808, 389, 2251, 2507, 548, 16, 2254, 5034, 8808, 389, 2293, 548, 16, 2254, 5034, 389, 5508, 16, 1758, 389, 1154, 264, 1769, 203, 565, 871, 776, 16474, 12, 11890, 5034, 8808, 389, 2251, 2507, 734, 16, 1426, 389, 3276, 16, 1758, 8808, 389, 90, 20005, 1769, 203, 565, 871, 3035, 2507, 19338, 56, 454, 2092, 12, 11890, 5034, 8808, 389, 2251, 2507, 734, 16, 509, 5034, 389, 2088, 16, 1758, 8808, 389, 266, 1798, 2930, 264, 16, 1758, 389, 20904, 17619, 16, 1426, 389, 3535, 1769, 203, 203, 203, 203, 565, 445, 2376, 1669, 2507, 12, 21009, 280, 3245, 18, 21009, 280, 3245, 3823, 2502, 365, 16, 2254, 5034, 389, 2293, 548, 16, 2254, 5034, 389, 5508, 16, 2254, 5034, 389, 1154, 264, 1016, 13, 1071, 288, 203, 3639, 29860, 280, 3245, 18, 691, 2502, 389, 2293, 273, 365, 18, 2293, 3790, 63, 67, 2293, 548, 15533, 203, 3639, 2583, 24899, 2293, 18, 1154, 329, 1768, 2578, 63, 67, 5508, 65, 405, 374, 16, 315, 49, 1920, 1203, 353, 374, 8863, 203, 3639, 2583, 24899, 1154, 264, 1016, 411, 1381, 16, 315, 2930, 264, 770, 353, 7194, 8863, 203, 3639, 1758, 389, 1154, 264, 273, 389, 2293, 18, 1154, 414, 30110, 63, 67, 5508, 6362, 67, 1154, 264, 1016, 15533, 203, 3639, 1731, 1578, 389, 2816, 273, 417, 24410, 2 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Faucet is Ownable { address public constant zebraToken = 0xeED62950d07f80d2890B418871055846ACB6b9d0; IERC20 Token = IERC20(zebraToken); uint8 private constant TOKEN_DECIMALS = 18; uint256 public constant waitTime = 5 minutes; mapping(address => uint256) lastAccessTime; // receive() external payable {} function withdraw() external allowedToWithdraw { Token.transfer(msg.sender, 100 * (10**TOKEN_DECIMALS)); lastAccessTime[msg.sender] = block.timestamp; } function liquidate(uint256 _amount) external onlyOwner { // Make sure faucet has tokens available to withdraw require( Token.balanceOf(address(this)) > 0, "Faucet balance insufficient." ); // Allow owner to withdraw all tokens in the contract by entering 0 if (_amount == 0) { _amount = Token.balanceOf(address(this)); } Token.transfer(msg.sender, _amount); } modifier allowedToWithdraw() { // Make sure faucet has tokens available to withdraw require( Token.balanceOf(address(this)) > 100 * (10**TOKEN_DECIMALS), "Faucet balance insufficient." ); // Don't allow user to withdraw more than 100 tokens every 5 minutes require( block.timestamp >= lastAccessTime[msg.sender] + waitTime, "You must wait 5 minutes between withdrawals." ); _; } }
Make sure faucet has tokens available to withdraw Allow owner to withdraw all tokens in the contract by entering 0
function liquidate(uint256 _amount) external onlyOwner { require( Token.balanceOf(address(this)) > 0, "Faucet balance insufficient." ); if (_amount == 0) { _amount = Token.balanceOf(address(this)); } Token.transfer(msg.sender, _amount); }
1,080,035
[ 1, 6464, 3071, 11087, 5286, 278, 711, 2430, 2319, 358, 598, 9446, 7852, 3410, 358, 598, 9446, 777, 2430, 316, 326, 6835, 635, 19014, 374, 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, 4501, 26595, 340, 12, 11890, 5034, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 3155, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 16, 203, 5411, 315, 29634, 5286, 278, 11013, 2763, 11339, 1199, 203, 3639, 11272, 203, 3639, 309, 261, 67, 8949, 422, 374, 13, 288, 203, 5411, 389, 8949, 273, 3155, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 289, 203, 3639, 3155, 18, 13866, 12, 3576, 18, 15330, 16, 389, 8949, 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 ]
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library 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]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 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; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.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 {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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 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; } // File deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, 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, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 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; } // File interfaces/digg/IMedianOracle.sol pragma solidity ^0.6.8; interface IMedianOracle { /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external; function reportExpirationTimeSec() external view returns(uint256); } // File contracts/digg-oracles/CentralizedOracle.sol pragma solidity 0.6.12; contract CentralizedOracle is AccessControlUpgradeable, PausableUpgradeable { bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE"); address public medianOracle; uint256 public proposedPayload; address public lastProposer; event PushReport(uint256 payload); function initialize(address medianOracle_, address initialAdmin_, address initialGuardian_, address[] memory initialOracles_) external initializer { __AccessControl_init(); __Pausable_init_unchained(); medianOracle = medianOracle_; _setupRole(DEFAULT_ADMIN_ROLE, initialAdmin_); _setupRole(GUARDIAN_ROLE, initialGuardian_); for (uint i = 0; i < initialOracles_.length; i++) { _setupRole(ORACLE_ROLE, initialOracles_[i]); } } // ===== Access Control Modifiers ===== modifier onlyOracle() { require(hasRole(ORACLE_ROLE, msg.sender), "ORACLE_ROLE"); _; } modifier onlyGuardian() { require(hasRole(GUARDIAN_ROLE, msg.sender), "GUARDIAN_ROLE"); _; } // ===== Permissioned Actions: Oracle ===== function proposeReport(uint256 payload) public onlyOracle { lastProposer = msg.sender; proposedPayload = payload; } function approveReport(uint256 payload) public onlyOracle { require(msg.sender != lastProposer, "Report proposer cannot approve own report"); IMedianOracle(medianOracle).pushReport(proposedPayload); } // ===== Permissioned Actions: Guardian ===== function pause() public onlyGuardian { pause(); } function unpause() public onlyGuardian { unpause(); } }
* @dev Library for managing 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 { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` (`UintSet`) are supported./ 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.
library EnumerableSetUpgradeable { struct Set { bytes32[] _values; mapping (bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } } else { function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._values.pop(); delete set._indexes[value]; return true; return false; } } else { }
1,338,662
[ 1, 9313, 364, 30632, 1953, 18, 11511, 1240, 326, 3751, 1790, 30, 300, 17219, 854, 3096, 16, 3723, 16, 471, 5950, 364, 15782, 316, 5381, 813, 261, 51, 12, 21, 13, 2934, 300, 17219, 854, 3557, 690, 316, 531, 12, 82, 2934, 2631, 28790, 854, 7165, 603, 326, 9543, 18, 31621, 6835, 5090, 288, 377, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 377, 6057, 25121, 694, 18, 1887, 694, 3238, 3399, 694, 31, 289, 31621, 2970, 434, 331, 23, 18, 20, 18, 20, 16, 1338, 1678, 434, 618, 1375, 2867, 68, 21863, 1887, 694, 24065, 471, 1375, 11890, 5034, 68, 21863, 5487, 694, 24065, 854, 3260, 18, 19, 2974, 2348, 333, 5313, 364, 3229, 1953, 598, 487, 12720, 981, 31239, 487, 3323, 16, 732, 1045, 518, 316, 6548, 434, 279, 5210, 1000, 618, 598, 1731, 1578, 924, 18, 1021, 1000, 4471, 4692, 3238, 4186, 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, 12083, 6057, 25121, 694, 10784, 429, 288, 203, 203, 203, 203, 203, 565, 1958, 1000, 288, 203, 3639, 1731, 1578, 8526, 389, 2372, 31, 203, 203, 3639, 2874, 261, 3890, 1578, 516, 2254, 5034, 13, 389, 11265, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 389, 4479, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 460, 1016, 273, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 203, 5411, 2254, 5034, 358, 2613, 1016, 273, 460, 1016, 300, 404, 31, 203, 5411, 2254, 5034, 7536, 273, 444, 6315, 2372, 18, 2469, 2 ]
// 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; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: 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: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns (address); function getModuleFee(address _module, uint256 _feeType) external view returns (uint256); function isModule(address _module) external view returns (bool); function isSet(address _setToken) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IIntegrationRegistry { function addIntegration( address _module, string memory _id, address _wrapper ) external; function getIntegrationAdapter(address _module, string memory _id) external view returns (address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns (address); function isValidIntegration(address _module, string memory _id) external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit( address _component, address _positionModule, int256 _realUnit ) external; function editExternalPositionData( address _component, address _positionModule, bytes calldata _data ) external; function invoke( address _target, uint256 _value, bytes calldata _data ) external returns (bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns (int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns (int256); function getComponents() external view returns (address[] memory); function getExternalPositionModules(address _component) external view returns (address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns (bytes memory); function isExternalPositionModule(address _component, address _module) external view returns (bool); function isComponent(address _component) external view returns (bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns (int256); function isInitializedModule(address _module) external view returns (bool); function isPendingModule(address _module) external view returns (bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {ISetToken} from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns (bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A, ) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint256[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom(_token, _from, _to, _quantity); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require(newBalance == existingBalance.add(_quantity), "Invalid post transfer balance"); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals( uint256 a, uint256 b, uint256 range ) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature( "approve(address,uint256)", _spender, _quantity ); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require(newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance"); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {ExplicitERC20} from "../../lib/ExplicitERC20.sol"; import {IController} from "../../interfaces/IController.sol"; import {IModule} from "../../interfaces/IModule.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {Invoke} from "./Invoke.sol"; import {Position} from "./Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; import {ResourceIdentifier} from "./ResourceIdentifier.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns (address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns (address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns (uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken( ISetToken _setToken, address _token, uint256 _feeQuantity ) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns (bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns (bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns (bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require(controller.isModule(msg.sender), "Module must be enabled on controller"); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits( ISetToken _setToken, address _component, uint256 _unit ) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns (bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition( ISetToken _setToken, address _component, uint256 _newUnit ) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require( positionModules[0] == _module, "External positions must be 0 to remove component" ); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns (uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns ( uint256, uint256, uint256 ) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IController} from "../../interfaces/IController.sol"; import {IIntegrationRegistry} from "../../interfaces/IIntegrationRegistry.sol"; import {IPriceOracle} from "../../interfaces/IPriceOracle.sol"; import {ISetValuer} from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 internal constant INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 internal constant PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 internal constant SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } /* Copyright 2021 Memento Blockchain Pte. Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {IController} from "../../interfaces/IController.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IIntegrationRegistry} from "../../interfaces/IIntegrationRegistry.sol"; import {Invoke} from "../lib/Invoke.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {ModuleBase} from "../lib/ModuleBase.sol"; import {Position} from "../lib/Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title DextfTradeModule * @author DEXTF Protocol * * Module that enables DEXTF fund managers to propose a new trade. If this trade is approved and * not blocked, after the proposal period, the fund manager can transition to the fund to the trading * state, where market makers can rebalance the fund by sending inbound components and recieving the * outbound ones as specified by the proposed trade. */ contract DextfTradeModule is ModuleBase, ReentrancyGuard, AccessControl { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using SafeCast for int256; using SafeMath for uint256; // **** Enumerations enum FundState { REGULAR, PROPOSAL, TRADING } // **** Data structures struct ProposalConstraints { // The minimum time delay between the proposal state and the trading state uint256 minimumDelay; // The minimum number of approver votes to transition to the trading state uint256 minimumApproverVotes; // The minimum number of blocker votes needed to stop a trade proposal uint256 minimumBlockerVotes; } struct TradeComponent { // The address of the component to be traded address componentAddress; // The traded quantity, in real units uint256 tradeRealUnits; } struct ProposedTrade { // The Specific contraints for this proposal ProposalConstraints proposalConstraints; // The list of trade components that will be sent to the fund when trading TradeComponent[] inboundTradeComponents; // The list of trade components that will be sent to the trader when trading TradeComponent[] outboundTradeComponents; // The maximum number of fund tokens that can be traded uint256 maxTradedFundTokens; // The number of fund tokens that have been traded so far uint256 tradedFundTokens; // The timestamp of the most-recent trade proposal uint256 proposalTimestamp; // The list of approvers that voted for the proposal, empty at the beginning of the proposal address[] approverVotes; // The list of blockers that voted against the proposal, empty at the beginning of the proposal address[] blockerVotes; } // **** Events event ProposalConstraintsUpdated( uint256 minimumDelay, uint256 minimumApproverVotes, uint256 minimumBlockerVotes ); event TradeProposed( ISetToken indexed fund, uint256 indexed proposalTimestamp, uint256 maxTradedFundTokens, uint256 minimumDelay, uint256 minimumApproverVotes, uint256 minimumBlockerVotes, uint256 inboundComponentsCount, uint256 outboundComponentsCount ); event ApprovalVoteCast( ISetToken indexed fund, uint256 indexed proposalTimestamp, address indexed voter ); event BlockerVoteCast( ISetToken indexed fund, uint256 indexed proposalTimestamp, address indexed voter ); event TradingStarted(ISetToken indexed fund, uint256 indexed proposalTimestamp); event InboundComponentReceived( ISetToken indexed setToken, uint256 indexed proposalTimestamp, address indexed marketMaker, address inToken, uint256 inboundAmount ); event OutboundComponentSent( ISetToken indexed setToken, uint256 indexed proposalTimestamp, address indexed marketMaker, address outToken, uint256 outboundAmount ); // **** Constants bytes32 public constant TRADE_ADMIN_ROLE = keccak256("TRADE_ADMIN_ROLE"); bytes32 public constant APPROVER_ROLE = keccak256("APPROVER_ROLE"); bytes32 public constant BLOCKER_ROLE = keccak256("BLOCKER_ROLE"); bytes32 public constant MARKET_MAKER_ROLE = keccak256("MARKET_MAKER_ROLE"); // **** State variables // These are the minimum values to be enforced for all trade proposal for all funds ProposalConstraints public moduleConstraints; // For each fund the relevant data for the current propsed trade mapping(ISetToken => ProposedTrade) public proposalDetails; // The state of each fund mapping(ISetToken => FundState) public fundState; // **** Constructor constructor( IController _controller, uint256 _minimumDelay, uint256 _minimumApproverVotes, uint256 _minimumBlockerVotes, address[] memory _administrators, address[] memory _approvers, address[] memory _blockers, address[] memory _marketMakers ) ModuleBase(_controller) { _setRoleAdmin(TRADE_ADMIN_ROLE, TRADE_ADMIN_ROLE); _setRoleAdmin(APPROVER_ROLE, TRADE_ADMIN_ROLE); _setRoleAdmin(BLOCKER_ROLE, TRADE_ADMIN_ROLE); _setRoleAdmin(MARKET_MAKER_ROLE, TRADE_ADMIN_ROLE); require(_administrators.length > 0, "At least one administrator is required"); // Register administrators for (uint256 i = 0; i < _administrators.length; ++i) { _setupRole(TRADE_ADMIN_ROLE, _administrators[i]); } // Register approvers for (uint256 i = 0; i < _approvers.length; ++i) { _setupRole(APPROVER_ROLE, _approvers[i]); } // Register blockers for (uint256 i = 0; i < _blockers.length; ++i) { _setupRole(BLOCKER_ROLE, _blockers[i]); } // Register market makers for (uint256 i = 0; i < _marketMakers.length; ++i) { _setupRole(MARKET_MAKER_ROLE, _marketMakers[i]); } _updateProposalConstraints(_minimumDelay, _minimumApproverVotes, _minimumBlockerVotes); } // **** Modifiers /** * @dev Modifier to make a function callable only by a certain role. */ modifier onlyRole(bytes32 role) { require(hasRole(role, _msgSender()), "Sender requires permission"); _; } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { require( hasRole(role, _msgSender()) || hasRole(role, address(0)), "Sender requires permission, or open role" ); _; } // **** External functions called by the SetToken smart contract /** * Initializes this module to the SetToken. Only callable by the SetToken's manager. * * @param _fund Address of the SetToken */ function initialize(ISetToken _fund) external onlySetManager(_fund, msg.sender) onlyValidAndPendingSet(_fund) { fundState[_fund] = FundState.REGULAR; _fund.initializeModule(); } /** * Called by a SetToken to notify that this module was removed. * Clears the proposalDetails and the fundState. */ function removeModule() external override { delete proposalDetails[ISetToken(msg.sender)]; delete fundState[ISetToken(msg.sender)]; } // **** External functions called only by the trade administrator /** * ONLY BY ADMINISTRATOR: updates the module-wide proposal constraints. * * @param _minimumDelay The minimum time delay between the proposal state and the trading state * @param _minimumApproverVotes The minimum number of approver votes to transition to the trading state * @param _minimumBlockerVotes The minimum number of blocker votes needed to stop a trade proposal */ function updateProposalConstraints( uint256 _minimumDelay, uint256 _minimumApproverVotes, uint256 _minimumBlockerVotes ) external nonReentrant onlyRole(TRADE_ADMIN_ROLE) { _updateProposalConstraints(_minimumDelay, _minimumApproverVotes, _minimumBlockerVotes); } // **** External functions called by the fund manager /** * ONLY FUND MANAGER: regardless of the current fund state, transition the fund to the regular state. * It can be use both to cancel a prposal or to cancel trading. * * @param _fund Address of the fund to be transitioned to the regular state */ function revertToRegularState(ISetToken _fund) external onlyManagerAndValidSet(_fund) { require(fundState[_fund] != FundState.REGULAR, "Already in regular state"); fundState[_fund] = FundState.REGULAR; } /** * ONLY FUND MANAGER: propose a new trade together with new constraint and transition a fund * from the regular state to the proposal state. There are no checks on the proposed trade as * these checks are left to the approvers and blockers. * * @param _fund Address of the fund subject of the trade * @param _maxTradedFundTokens The maximum number of fund tokens that can be traded * @param _proposalConstraints The constraints for this proposal * @param _inboundAddresses The component addresses entering the fund * @param _outboundAddresses The component addresses exiting the fund * @param _inboundRealUnitsArray The value of the incoming tokens per fund token, in real units * @param _outboundRealUnitsArray The value of the outgoing tokens per fund token, in real units */ function proposeTrade( ISetToken _fund, uint256 _maxTradedFundTokens, ProposalConstraints calldata _proposalConstraints, address[] calldata _inboundAddresses, uint256[] calldata _inboundRealUnitsArray, address[] calldata _outboundAddresses, uint256[] calldata _outboundRealUnitsArray ) external onlyManagerAndValidSet(_fund) { // Check that the fund was in the regular state require(fundState[_fund] == FundState.REGULAR, "Fund must be in the regular state"); // Check that the proposal constraints are compatible with the module-wise constraints require( _proposalConstraints.minimumDelay >= moduleConstraints.minimumDelay, "minimum delay too short" ); require( _proposalConstraints.minimumApproverVotes >= moduleConstraints.minimumApproverVotes, "minimum approvers too small" ); require( _proposalConstraints.minimumBlockerVotes >= moduleConstraints.minimumBlockerVotes, "minimum blockers too small" ); // Check that the proposed trade is not empty require(_inboundAddresses.length > 0, "Inbound addresses cannot be empty"); require(_outboundAddresses.length > 0, "Outbound addresses cannot be empty"); // Check for vector consistency require(_inboundRealUnitsArray.length == _inboundAddresses.length, "Mismatch inbound lenghts"); require( _outboundAddresses.length == _outboundRealUnitsArray.length, "Mismatch outbound lenghts" ); // Make sure there is no null address in either inbound or outbound components require(!_inboundAddresses.contains(address(0)), "Null address in inbound componets"); require(!_outboundAddresses.contains(address(0)), "Null address in outbound componets"); // Check that there are non duplicate in the component addresses require( !_inboundAddresses.extend(_outboundAddresses).hasDuplicate(), "Duplicate components are not allowed" ); // Check that max number of fund tokens traded is bigger than 0 require(_maxTradedFundTokens > 0, "Max number of traded tokens must be bigger than 0"); // Keep track of the maxium tokens to be traded proposalDetails[_fund].maxTradedFundTokens = _maxTradedFundTokens; // Reset the number of fund tokens that have been traded so far proposalDetails[_fund].tradedFundTokens = 0; // Save the current block timestamp as the proposal timestamp // solhint-disable-next-line not-rely-on-time proposalDetails[_fund].proposalTimestamp = block.timestamp; // Update the proposal constraints and the new allocation components proposalDetails[_fund].proposalConstraints.minimumDelay = _proposalConstraints.minimumDelay; proposalDetails[_fund].proposalConstraints.minimumApproverVotes = _proposalConstraints .minimumApproverVotes; proposalDetails[_fund].proposalConstraints.minimumBlockerVotes = _proposalConstraints .minimumBlockerVotes; // Reset the previous proposal votes delete proposalDetails[_fund].approverVotes; delete proposalDetails[_fund].blockerVotes; // Destroy the previous and create the new inboundTradeComponents vector delete proposalDetails[_fund].inboundTradeComponents; // Loop and push the inbound components for (uint256 i = 0; i < _inboundAddresses.length; i++) { proposalDetails[_fund].inboundTradeComponents.push( TradeComponent({ componentAddress: _inboundAddresses[i], tradeRealUnits: _inboundRealUnitsArray[i] }) ); } // Destroy the previous and create the new outboundTradeComponents vector delete proposalDetails[_fund].outboundTradeComponents; // Loop and push the outbound components for (uint256 i = 0; i < _outboundAddresses.length; i++) { proposalDetails[_fund].outboundTradeComponents.push( TradeComponent({ componentAddress: _outboundAddresses[i], tradeRealUnits: _outboundRealUnitsArray[i] }) ); } // Check that outboud components are compatible with the current fund holdings _checkOutboundComponents(_fund); fundState[_fund] = FundState.PROPOSAL; emit TradeProposed( _fund, block.timestamp, _maxTradedFundTokens, _proposalConstraints.minimumDelay, _proposalConstraints.minimumApproverVotes, _proposalConstraints.minimumBlockerVotes, _inboundAddresses.length, _outboundAddresses.length ); } /** * ONLY FUND MANAGER: Transition the fund from the proposal state to the trading state if all * constranits are satifid: the minimum proposal time has elapsed, there are enough approval votes * and there are not too many blocker votes. * * @param _fund Address of the fund for which trading can start */ function startTrading(ISetToken _fund) external onlyManagerAndValidSet(_fund) { // Check that the fund was in the proposal state require(fundState[_fund] == FundState.PROPOSAL, "Fund must be in the proposal state"); // Check that we are after the proposed period require( block.timestamp >= proposalDetails[_fund].proposalTimestamp.add( proposalDetails[_fund].proposalConstraints.minimumDelay ), "Proposal period not over yet" ); // Check that there are not enough blocker votes if (proposalDetails[_fund].proposalConstraints.minimumBlockerVotes > 0) { require( proposalDetails[_fund].blockerVotes.length < proposalDetails[_fund].proposalConstraints.minimumBlockerVotes, "Too many blocker votes" ); } // Check that there are enough approval votes require( proposalDetails[_fund].approverVotes.length >= proposalDetails[_fund].proposalConstraints.minimumApproverVotes, "Not enough approval votes" ); // Transition the fund to the trading state fundState[_fund] = FundState.TRADING; emit TradingStarted(_fund, proposalDetails[_fund].proposalTimestamp); } // **** External functions called by approvers /** * ONLY APPROVERS: called by an approver to cast an approval vote to the latest proposal on a certain fund. * Once the vote is cast it cannot be retracted. * * @param _fund Address of the fund for which the approval vote is cast */ function castApprovalVote(ISetToken _fund) external onlyRole(APPROVER_ROLE) { // Check that the fund is in the proposal state require(fundState[_fund] == FundState.PROPOSAL, "Fund must be in proposal state"); // Check that this approver hasn't voted yet require( !proposalDetails[_fund].approverVotes.contains(msg.sender), "Approver has already voted" ); // Add the approval vote to the tally proposalDetails[_fund].approverVotes.push(msg.sender); emit ApprovalVoteCast(_fund, proposalDetails[_fund].proposalTimestamp, msg.sender); } // **** External functions called by blockers /** * ONLY BLOCKERS: called by a blocker to cast a blocking vote to the latest proposal on a certain fund. * Once the vote is cast it cannot be retracted. * * @param _fund Address of the fund for which the blocker vote is cast */ function castBlockerVote(ISetToken _fund) external onlyRole(BLOCKER_ROLE) { // Check that the fund is in the proposal state require(fundState[_fund] == FundState.PROPOSAL, "Fund must be in proposal state"); // Check that this blocker hasn't voted yet require(!proposalDetails[_fund].blockerVotes.contains(msg.sender), "Blocker has already voted"); // Add the approval vote to the tally proposalDetails[_fund].blockerVotes.push(msg.sender); emit BlockerVoteCast(_fund, proposalDetails[_fund].proposalTimestamp, msg.sender); } // **** External functions called by market makers /** * ONLY MARKET MAKERS: called by market makers to perform the actual trade by sending inboud components * and receiveing outbound ones. * * @param _fund Address of the fund for which want to perform the trade * @param _quantity The equivalent number of fund tokens to be traded * */ function performTrade(ISetToken _fund, uint256 _quantity) external nonReentrant onlyRoleOrOpenRole(MARKET_MAKER_ROLE) { // Check that the fund is in the trading state require(fundState[_fund] == FundState.TRADING, "Fund must be in trading state"); // Check that the quantity is positive require(_quantity > 0, "Quantity must be positive"); // Compute total fund supply uint256 fundTotalSupply = _fund.totalSupply(); // Check that the quantity is not larger than the total supply require(_quantity <= fundTotalSupply, "Quantity exceeds total supply"); // Check that we do traded more fund tokens than originally intended uint256 newTotalQuantity = proposalDetails[_fund].tradedFundTokens.add(_quantity); require( newTotalQuantity <= proposalDetails[_fund].maxTradedFundTokens, "Maximum quantity of traded fund tokens exceeded" ); // We need to perform this check again because the positions might have changed since proposal _checkOutboundComponents(_fund); // We store the component current balances before trading, to keep track of airdrops uint256[] memory preTradeInboundBalances = _computePreTradeBalances( _fund, proposalDetails[_fund].inboundTradeComponents ); uint256[] memory preTradeOutboundBalances = _computePreTradeBalances( _fund, proposalDetails[_fund].outboundTradeComponents ); // Compute quantity-scaled inbound/outbound components ( TradeComponent[] memory scaledInboundComponents, TradeComponent[] memory scaledOutboundComponents ) = _scaleComponents(_fund, _quantity); // Trade the outbound components for the inbound ones _tradeInboundComponents(_fund, scaledInboundComponents); _tradeOutboundComponents(_fund, scaledOutboundComponents); // Update the fund positions after the trade _updateFundPositions( _fund, proposalDetails[_fund].inboundTradeComponents, fundTotalSupply, preTradeInboundBalances ); _updateFundPositions( _fund, proposalDetails[_fund].outboundTradeComponents, fundTotalSupply, preTradeOutboundBalances ); // Update the quanity if tokens traded so far proposalDetails[_fund].tradedFundTokens = newTotalQuantity; } // **** External views /** * Returns the latest proposal details for a given fund. * * @param _fund Address of the fund for which the proposal details are needed * * @return proposalDetails The latest trade proposal details for the given fund */ function getProposalDetails(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (ProposedTrade memory) { return proposalDetails[_fund]; } /** * Retrieves the timestamp of the current fund proposal. * * @param _fund Fund for which we want to query the proposal timestamp * * @return proposalTimestamp The latest proposal timestamp for the given fund */ function getProposalTimestamp(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (uint256) { return proposalDetails[_fund].proposalTimestamp; } /** * Retrieves the constraints of the current fund proposal. * * @param _fund Fund for which we want to query the proposal constraints * * @return minimumDelay The minimum time delay between the proposal state and the trading state * @return minimumApproverVotes The minimum number of approver votes to transition to the trading state * @return minimumBlockerVotes he minimum number of blocker votes needed to stop a proposal */ function getProposalConstraints(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns ( uint256, uint256, uint256 ) { return ( proposalDetails[_fund].proposalConstraints.minimumDelay, proposalDetails[_fund].proposalConstraints.minimumApproverVotes, proposalDetails[_fund].proposalConstraints.minimumBlockerVotes ); } /** * Retrieves the proposed inbound allocation components, in real units. * * @param _fund Fund for which we want to query the inbound components * * @return _componentAddresses The addresses of the proposed inbound components * @return _positionRealUnitsArray The value of the inbound component flow */ function getProposedInboundComponents(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (address[] memory, uint256[] memory) { // Allocate the memory for the arrays address[] memory componentAddresses = new address[]( proposalDetails[_fund].inboundTradeComponents.length ); uint256[] memory tradeRealUnitsArray = new uint256[]( proposalDetails[_fund].inboundTradeComponents.length ); // Transpose the inboundTradeComponents array for (uint256 i = 0; i < proposalDetails[_fund].inboundTradeComponents.length; i++) { componentAddresses[i] = proposalDetails[_fund].inboundTradeComponents[i].componentAddress; tradeRealUnitsArray[i] = proposalDetails[_fund].inboundTradeComponents[i].tradeRealUnits; } return (componentAddresses, tradeRealUnitsArray); } /** * Retrieves the proposed outbound allocation components, in real units. * * @param _fund Fund for which we want to query the outbound components * * @return _componentAddresses The addresses of the proposed outbound components * @return _positionRealUnitsArray The value of the outbound component flow */ function getProposedOutboundComponents(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (address[] memory, uint256[] memory) { // Allocate the memory for the arrays address[] memory componentAddresses = new address[]( proposalDetails[_fund].outboundTradeComponents.length ); uint256[] memory tradeRealUnitsArray = new uint256[]( proposalDetails[_fund].outboundTradeComponents.length ); // Transpose the outboundTradeComponents array for (uint256 i = 0; i < proposalDetails[_fund].outboundTradeComponents.length; i++) { componentAddresses[i] = proposalDetails[_fund].outboundTradeComponents[i].componentAddress; tradeRealUnitsArray[i] = proposalDetails[_fund].outboundTradeComponents[i].tradeRealUnits; } return (componentAddresses, tradeRealUnitsArray); } /** * Retrieves the latest tally of the approver votes cast on the most recent proposal. * * @param _fund Fund for which we want to query the approver votes * * @return approverVotes The array of approvers that cast a vote on the latest proposal */ function getApprovalVotes(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (address[] memory) { return proposalDetails[_fund].approverVotes; } /** * Retrieves the latest tally of the blocker votes cast on the most recent proposal. * * @param _fund Fund for which we want to query the blocker votes * * @return blockerVotes The array of blockers that cast a vote on the latest proposal */ function getBlockerVotes(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (address[] memory) { return proposalDetails[_fund].blockerVotes; } /** * Retrieves the currently and maximum equivalent traded fund tokens * * @param _fund Fund for which we want to query the equivalent traded fund tokens * * @return tradedFundTokens The equivalent number of fund tokens that have been traded so far * @return maxTradedFundTokens The maximum number of equivalent fund tokens that can be traded */ function getTradedFundTokens(ISetToken _fund) external view onlyValidAndInitializedSet(_fund) returns (uint256, uint256) { return (proposalDetails[_fund].tradedFundTokens, proposalDetails[_fund].maxTradedFundTokens); } /** * Compute the proposed/actual trade components according to the given quantity * * @param _fund Address of the fund subject of the trade * @param _quantity The number of fund base units to be traded * * @return address[] The array of inbound addresses * @return uint256[] The array of inbound quantities in real units * @return address[] The array of outbound addresses * @return uint256[] The array of outbound quantities in real units */ function computeInboundOutboundComponents(ISetToken _fund, uint256 _quantity) public view onlyValidAndInitializedSet(_fund) returns ( address[] memory, uint256[] memory, address[] memory, uint256[] memory ) { // Compute quantity-scaled inbound/outbound components ( TradeComponent[] memory scaledInboundComponents, TradeComponent[] memory scaledOutboundComponents ) = _scaleComponents(_fund, _quantity); // Reserve the correct memory space for all arrays address[] memory inboundAddresses = new address[](scaledInboundComponents.length); uint256[] memory inboundRealUnitsArray = new uint256[](scaledInboundComponents.length); address[] memory outboundAddresses = new address[](scaledOutboundComponents.length); uint256[] memory outboundRealUnitsArray = new uint256[](scaledOutboundComponents.length); // Traspose the inbound vectors for (uint256 i = 0; i < inboundAddresses.length; i++) { inboundAddresses[i] = scaledInboundComponents[i].componentAddress; inboundRealUnitsArray[i] = scaledInboundComponents[i].tradeRealUnits; } // Traspose the outbound vectors for (uint256 i = 0; i < outboundAddresses.length; i++) { outboundAddresses[i] = scaledOutboundComponents[i].componentAddress; outboundRealUnitsArray[i] = scaledOutboundComponents[i].tradeRealUnits; } return (inboundAddresses, inboundRealUnitsArray, outboundAddresses, outboundRealUnitsArray); } // **** Internal functions /** * Private function to update the module-wide minimum proposal constraints. * * @param _minimumDelay The minimum time delay between the proposal state and the trading state * @param _minimumApproverVotes The minimum number of approver votes to transition to the trading state * @param _minimumBlockerVotes The minimum number of blocker votes needed to stop a proposal */ function _updateProposalConstraints( uint256 _minimumDelay, uint256 _minimumApproverVotes, uint256 _minimumBlockerVotes ) internal { moduleConstraints.minimumDelay = _minimumDelay; moduleConstraints.minimumApproverVotes = _minimumApproverVotes; moduleConstraints.minimumBlockerVotes = _minimumBlockerVotes; emit ProposalConstraintsUpdated(_minimumDelay, _minimumApproverVotes, _minimumBlockerVotes); } /** * Trades the inbound components from the transaction sender to the fund contract. * Note that the tokens need to be approved before they can be transferred. * * @param _fund Address of the fund subject of the trade * @param _scaledInboundComponents The inbound components to be received */ function _tradeInboundComponents( ISetToken _fund, TradeComponent[] memory _scaledInboundComponents ) internal { // Transfer the inbound components for (uint256 i = 0; i < _scaledInboundComponents.length; i++) { transferFrom( IERC20(_scaledInboundComponents[i].componentAddress), msg.sender, address(_fund), _scaledInboundComponents[i].tradeRealUnits ); emit InboundComponentReceived( _fund, proposalDetails[_fund].proposalTimestamp, msg.sender, _scaledInboundComponents[i].componentAddress, _scaledInboundComponents[i].tradeRealUnits ); } } /** * Trades the outbound components from the fund contract to the transaction sender * * @param _fund Address of the fund subject of the trade * @param _scaledOutboundComponents The outbound components to be sent out */ function _tradeOutboundComponents( ISetToken _fund, TradeComponent[] memory _scaledOutboundComponents ) internal { // Transfer the outbound components for (uint256 i = 0; i < _scaledOutboundComponents.length; i++) { _fund.strictInvokeTransfer( _scaledOutboundComponents[i].componentAddress, msg.sender, _scaledOutboundComponents[i].tradeRealUnits ); emit OutboundComponentSent( _fund, proposalDetails[_fund].proposalTimestamp, msg.sender, _scaledOutboundComponents[i].componentAddress, _scaledOutboundComponents[i].tradeRealUnits ); } } /** * Update the fund positions according to the trades just executed * * @param _fund Address of the fund subject of the position update * @param _tradeComponents The components to be updated * @param _fundTotalSupply The observed fund total supply * @param _preTradePositionBalances The fund balance for each given component, observed before the trade */ function _updateFundPositions( ISetToken _fund, TradeComponent[] memory _tradeComponents, uint256 _fundTotalSupply, uint256[] memory _preTradePositionBalances ) internal { // Edit the inbound-component positions for (uint256 i = 0; i < _tradeComponents.length; i++) { _fund.calculateAndEditDefaultPosition( _tradeComponents[i].componentAddress, _fundTotalSupply, _preTradePositionBalances[i] ); } } /** * Makes sure that the requested outbound components do not exceed the current positions * * @param _fund Address of the fund subject of the trade */ function _checkOutboundComponents(ISetToken _fund) internal view { for (uint256 i = 0; i < proposalDetails[_fund].outboundTradeComponents.length; i++) { address tradeComponentAddress = proposalDetails[_fund] .outboundTradeComponents[i] .componentAddress; if (_fund.isComponent(tradeComponentAddress)) { uint256 outboundComponentRealUnits = proposalDetails[_fund] .outboundTradeComponents[i] .tradeRealUnits; uint256 currentRealUnits = _fund .getDefaultPositionRealUnit(tradeComponentAddress) .toUint256(); require( outboundComponentRealUnits <= currentRealUnits, "Insufficient balance for outbound component" ); } else { revert("Outbound component not in the fund"); } } } // **** Internal views /** * Computes the component balance before the trades. * * @param _fund Address of the fund subject of the trade * @param _tradeComponents The components to be traded and their quantities * * @return uint256[] The array if pre-trade balances */ function _computePreTradeBalances(ISetToken _fund, TradeComponent[] memory _tradeComponents) internal view returns (uint256[] memory) { // Allocate the memory array first uint256[] memory preTradeBalances = new uint256[](_tradeComponents.length); // Fetch the position balance and store it in the array for (uint256 i = 0; i < _tradeComponents.length; i++) { preTradeBalances[i] = IERC20(_tradeComponents[i].componentAddress).balanceOf(address(_fund)); } return preTradeBalances; } /** * Rescale the fund proposed/actual trade components according to the given quantity * * @param _fund Address of the fund subject of the trade * @param _quantity The number of fund base units to be traded * * @return TradeComponent[] The scaled inbound trade components * @return TradeComponent[] The scaled outbound trade components */ function _scaleComponents(ISetToken _fund, uint256 _quantity) internal view returns (TradeComponent[] memory, TradeComponent[] memory) { // Reserve the correct memory space for both inbound and outbound vectors TradeComponent[] memory _scaledInboundComponents = new TradeComponent[]( proposalDetails[_fund].inboundTradeComponents.length ); TradeComponent[] memory _scaledOutboundComponents = new TradeComponent[]( proposalDetails[_fund].outboundTradeComponents.length ); // Compute the scaled inbound components for (uint256 i = 0; i < _scaledInboundComponents.length; i++) { uint256 realUnit = proposalDetails[_fund].inboundTradeComponents[i].tradeRealUnits; // Use preciseMulCeil to be consistent with the BasicIssuance module issuance _scaledInboundComponents[i].tradeRealUnits = realUnit.preciseMulCeil(_quantity); _scaledInboundComponents[i].componentAddress = proposalDetails[_fund] .inboundTradeComponents[i] .componentAddress; } // Compute the scaled outbound components for (uint256 i = 0; i < _scaledOutboundComponents.length; i++) { uint256 realUnit = proposalDetails[_fund].outboundTradeComponents[i].tradeRealUnits; // Use preciseMul to be consistent with the BasicIssuance module redemption _scaledOutboundComponents[i].tradeRealUnits = _quantity.preciseMul(realUnit); _scaledOutboundComponents[i].componentAddress = proposalDetails[_fund] .outboundTradeComponents[i] .componentAddress; } return (_scaledInboundComponents, _scaledOutboundComponents); } }
**** External functions called by market makers* ONLY MARKET MAKERS: called by market makers to perform the actual trade by sending inboud components and receiveing outbound ones. @param _fund Address of the fund for which want to perform the trade @param _quantity The equivalent number of fund tokens to be traded/ Check that the fund is in the trading state Check that the quantity is positive Compute total fund supply Check that the quantity is not larger than the total supply Check that we do traded more fund tokens than originally intended We need to perform this check again because the positions might have changed since proposal We store the component current balances before trading, to keep track of airdrops Compute quantity-scaled inbound/outbound components Trade the outbound components for the inbound ones Update the fund positions after the trade Update the quanity if tokens traded so far
function performTrade(ISetToken _fund, uint256 _quantity) external nonReentrant onlyRoleOrOpenRole(MARKET_MAKER_ROLE) { require(fundState[_fund] == FundState.TRADING, "Fund must be in trading state"); require(_quantity > 0, "Quantity must be positive"); uint256 fundTotalSupply = _fund.totalSupply(); require(_quantity <= fundTotalSupply, "Quantity exceeds total supply"); uint256 newTotalQuantity = proposalDetails[_fund].tradedFundTokens.add(_quantity); require( newTotalQuantity <= proposalDetails[_fund].maxTradedFundTokens, "Maximum quantity of traded fund tokens exceeded" ); _checkOutboundComponents(_fund); uint256[] memory preTradeInboundBalances = _computePreTradeBalances( _fund, proposalDetails[_fund].inboundTradeComponents ); uint256[] memory preTradeOutboundBalances = _computePreTradeBalances( _fund, proposalDetails[_fund].outboundTradeComponents ); ( TradeComponent[] memory scaledInboundComponents, TradeComponent[] memory scaledOutboundComponents ) = _scaleComponents(_fund, _quantity); _tradeInboundComponents(_fund, scaledInboundComponents); _tradeOutboundComponents(_fund, scaledOutboundComponents); _updateFundPositions( _fund, proposalDetails[_fund].inboundTradeComponents, fundTotalSupply, preTradeInboundBalances ); _updateFundPositions( _fund, proposalDetails[_fund].outboundTradeComponents, fundTotalSupply, preTradeOutboundBalances ); proposalDetails[_fund].tradedFundTokens = newTotalQuantity; }
10,220,736
[ 1, 6841, 4186, 2566, 635, 13667, 29796, 414, 20747, 20503, 1584, 490, 14607, 11367, 30, 2566, 635, 13667, 29796, 414, 358, 3073, 326, 3214, 18542, 635, 5431, 316, 1075, 1100, 4085, 471, 6798, 310, 11663, 5945, 18, 225, 389, 74, 1074, 1377, 5267, 434, 326, 284, 1074, 364, 1492, 2545, 358, 3073, 326, 18542, 225, 389, 16172, 225, 1021, 7680, 1300, 434, 284, 1074, 2430, 358, 506, 1284, 785, 19, 2073, 716, 326, 284, 1074, 353, 316, 326, 1284, 7459, 919, 2073, 716, 326, 10457, 353, 6895, 8155, 2078, 284, 1074, 14467, 2073, 716, 326, 10457, 353, 486, 10974, 2353, 326, 2078, 14467, 2073, 716, 732, 741, 1284, 785, 1898, 284, 1074, 2430, 2353, 24000, 12613, 1660, 1608, 358, 3073, 333, 866, 3382, 2724, 326, 6865, 4825, 1240, 3550, 3241, 14708, 1660, 1707, 326, 1794, 783, 324, 26488, 1865, 1284, 7459, 16, 358, 3455, 3298, 434, 279, 6909, 16703, 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, 3073, 22583, 12, 45, 694, 1345, 389, 74, 1074, 16, 2254, 5034, 389, 16172, 13, 203, 565, 3903, 203, 565, 1661, 426, 8230, 970, 203, 565, 1338, 2996, 1162, 3678, 2996, 12, 12693, 1584, 67, 5535, 27221, 67, 16256, 13, 203, 225, 288, 203, 565, 2583, 12, 74, 1074, 1119, 63, 67, 74, 1074, 65, 422, 478, 1074, 1119, 18, 4349, 30118, 16, 315, 42, 1074, 1297, 506, 316, 1284, 7459, 919, 8863, 203, 203, 565, 2583, 24899, 16172, 405, 374, 16, 315, 12035, 1297, 506, 6895, 8863, 203, 203, 565, 2254, 5034, 284, 1074, 5269, 3088, 1283, 273, 389, 74, 1074, 18, 4963, 3088, 1283, 5621, 203, 203, 565, 2583, 24899, 16172, 1648, 284, 1074, 5269, 3088, 1283, 16, 315, 12035, 14399, 2078, 14467, 8863, 203, 203, 565, 2254, 5034, 394, 5269, 12035, 273, 14708, 3790, 63, 67, 74, 1074, 8009, 2033, 785, 42, 1074, 5157, 18, 1289, 24899, 16172, 1769, 203, 565, 2583, 12, 203, 1377, 394, 5269, 12035, 1648, 14708, 3790, 63, 67, 74, 1074, 8009, 1896, 1609, 785, 42, 1074, 5157, 16, 203, 1377, 315, 13528, 10457, 434, 1284, 785, 284, 1074, 2430, 12428, 6, 203, 565, 11272, 203, 203, 565, 389, 1893, 17873, 7171, 24899, 74, 1074, 1769, 203, 203, 565, 2254, 5034, 8526, 3778, 675, 22583, 20571, 38, 26488, 273, 389, 9200, 1386, 22583, 38, 26488, 12, 203, 1377, 389, 74, 1074, 16, 203, 1377, 14708, 3790, 63, 67, 74, 1074, 8009, 267, 3653, 22583, 7171, 203, 565, 11272, 203, 203, 565, 2254, 5034, 8526, 3778, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./KDZTokenConfig.sol"; // ---------------------------------------------------------------------------- // KDZTokens - TREES NFT Contract // // Copyright (c) 2021 SAFETREES SPACE. // https://safetrees.space/ // // ---------------------------------------------------------------------------- contract KDZTokens is ERC721, KDZTokenConfig, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Tracker for tokenId */ Counters.Counter private _tokenIdTracker; /** * @dev Emitted when `tokenId` token is minted from `to`. */ event Mint(address indexed to, uint256 indexed tokenId); // base URI string private _baseTokenURI; /** * @dev Media links to store tokenId image for inventory */ mapping(uint256 => string) _tokenURIs; constructor() ERC721(TOKEN_NAME, TOKEN_SYMBOL) { // setup roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, string memory _tokenURI) public virtual { require( hasRole(MINTER_ROLE, _msgSender()), "KDZTokens: must have minter role to mint." ); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. uint256 tokenId = _tokenIdTracker.current(); // if `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer _safeMint(to, tokenId); // link to the meta data of token ID _setTokenURI(tokenId, _tokenURI); // increase token id _tokenIdTracker.increment(); // raise event token minted emit Mint(to, tokenId); } /** * @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) public virtual returns (bool) { return _exists(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { // require that token should exist require(_exists(tokenId), "KDZTokens: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Public function to set the base URI for all token IDs. */ function setTokenBaseURI(string memory _baseURI) public { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "KDZTokens: must have admin role to set base URI." ); // call internal function _baseTokenURI = _baseURI; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "KDZTokens: must have pauser role to pause." ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "KDZTokens: must have pauser role to unpause." ); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {IERC721Metadata-tokenURI}. * Requirements: * * - `tokenId` must exist. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { // require that token should exist require(_exists(tokenId), "KDZTokens: 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, Strings.toString(tokenId))); } /** * @dev Returns the base URI set via setTokenBaseURI function. 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 _baseTokenURI; } /** * @dev return currently number of token issued */ function getTotalSupply() public view returns (uint256 totalSupply) { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "KDZTokens: you must be ADMIN to use this function." ); // get token total supply totalSupply = _tokenIdTracker.current(); return totalSupply; } }
* @dev Unpauses all token transfers. See {ERC721Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./
function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "KDZTokens: must have pauser role to unpause." ); _unpause(); }
13,032,349
[ 1, 984, 8774, 6117, 777, 1147, 29375, 18, 2164, 288, 654, 39, 27, 5340, 16507, 16665, 97, 471, 288, 16507, 16665, 17, 67, 318, 19476, 5496, 29076, 30, 300, 326, 4894, 1297, 1240, 326, 1375, 4066, 4714, 67, 16256, 8338, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 640, 19476, 1435, 1071, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 28335, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 47, 40, 62, 5157, 30, 1297, 1240, 6790, 1355, 2478, 358, 640, 19476, 1199, 203, 3639, 11272, 203, 3639, 389, 318, 19476, 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 ]
./full_match/5/0x24EbD77985F015DefEe0579449dAcbe58c1Ac25c/sources/project:/contracts/MedicalRecordAccessControl.sol
To ensure unique patient IDs
mapping(uint256 => bool) private usedPatientIDs;
1,871,905
[ 1, 774, 3387, 3089, 18608, 7115, 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, 2874, 12, 11890, 5034, 516, 1426, 13, 3238, 1399, 22834, 1979, 5103, 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.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ECRecovery.sol"; import "./utils/GetCode2.sol"; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; contract IERC20 { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Enigma { using SafeMath for uint256; using ECRecovery for bytes32; // The interface of the deployed ENG ERC20 token contract IERC20 public engToken; // The data representation of a computation task struct Task { address dappContract; TaskStatus status; string callable; bytes callableArgs; string callback; address worker; bytes sig; uint256 reward; uint256 blockNumber; } enum TaskStatus {InProgress, Executed} enum ReturnValue {Ok, Error} /** * The signer address of the principal node * This must be set when deploying the contract and remains immutable * Since the signer address is derived from the public key of an * SGX enclave, this ensures that the principal node cannot be tempered * with or replaced. */ address principal; // The data representation of a worker (or node) struct Worker { address signer; uint8 status; // Uninitialized: 0; Active: 1; Inactive: 2 bytes report; // Decided to store this as one RLP encoded attribute for easier external storage in the future uint256 balance; } /** * The data representation of the worker parameters used as input for * the worker selection algorithm */ struct WorkersParams { uint256 firstBlockNumber; address[] workerAddresses; uint256 seed; } /** * The last 5 worker parameters * We keep a collection of worker parameters to account for latency issues. * A computation task might be conceivably given out at a certain block number * but executed at a later block in a different epoch. It follows that * the contract must have access to the worker parameters effective when giving * out the task, otherwise the selected worker would not match. We calculated * that keeping the last 5 items should be more than enough to account for * all latent tasks. Tasks results will be rejected past this limit. */ WorkersParams[5] workersParams; // An address-based index of all registered worker address[] public workerAddresses; // A registry of all registered workers with their attributes mapping(address => Worker) public workers; // A registry of all active and historical tasks with their attributes // TODO: do we keep tasks forever? if not, when do we delete them? mapping(bytes32 => Task) public tasks; // The events emitted by the contract event Register(address custodian, address signer, bool _success); event ValidatedSig(bytes sig, bytes32 hash, address workerAddr, bool _success); event CommitResults(address dappContract, address worker, bytes sig, uint reward, bool _success); event WorkersParameterized(uint256 seed, address[] workers, bool _success); event ComputeTask( address indexed dappContract, bytes32 indexed taskId, string callable, bytes callableArgs, string callback, uint256 fee, bytes32[] preprocessors, uint256 blockNumber, bool _success ); constructor(address _tokenAddress, address _principal) public { engToken = IERC20(_tokenAddress); principal = _principal; } /** * Checks if the custodian wallet is registered as a worker * * @param user The custodian address of the worker */ modifier workerRegistered(address user) { Worker memory worker = workers[user]; require(worker.status > 0, "Unregistered worker."); _; } /** * Registers a new worker of change the signer parameters of an existing * worker. This should be called by every worker (and the principal) * node in order to receive tasks. * * @param signer The signer address, derived from the enclave public key * @param report The RLP encoded report returned by the IAS */ function register(address signer, bytes report) public payable returns (ReturnValue) { // TODO: consider exit if both signer and custodian as matching // If the custodian is not already register, we add an index entry if (workers[msg.sender].signer == 0x0) { uint index = workerAddresses.length; workerAddresses.length++; workerAddresses[index] = msg.sender; } // Set the custodian attributes workers[msg.sender].signer = signer; workers[msg.sender].balance = msg.value; workers[msg.sender].report = report; workers[msg.sender].status = 1; emit Register(msg.sender, signer, true); return ReturnValue.Ok; } /** * Generates a unique task id * * @param dappContract The address of the deployed contract containing the callable method * @param callable The signature (as defined by the Ethereum ABI) of the function to compute * @param callableArgs The RLP serialized arguments of the callable function * @param blockNumber The current block number * @return The task id */ function generateTaskId(address dappContract, string callable, bytes callableArgs, uint256 blockNumber) public pure returns (bytes32) { bytes32 hash = keccak256(abi.encodePacked(dappContract, callable, callableArgs, blockNumber)); return hash; } /** * Give out a computation task to the network * * @param dappContract The address of the deployed contract containing the callable method * @param callable The signature (as defined by the Ethereum ABI) of the function to compute * @param callableArgs The RLP serialized arguments of the callable function * @param callback The signature of the function to call back with the results * @param fee The computation fee in ENG * @param preprocessors A list of preprocessors to run and inject as argument of callable * @param blockNumber The current block number */ function compute( address dappContract, string callable, bytes callableArgs, string callback, uint256 fee, bytes32[] preprocessors, uint256 blockNumber ) public returns (ReturnValue) { // TODO: Add a multiplier to the fee (like ETH => wei) in order to accept smaller denominations bytes32 taskId = generateTaskId(dappContract, callable, callableArgs, blockNumber); require(tasks[taskId].dappContract == 0x0, "Task with the same taskId already exist"); tasks[taskId].reward = fee; tasks[taskId].callable = callable; tasks[taskId].callableArgs = callableArgs; tasks[taskId].callback = callback; tasks[taskId].status = TaskStatus.InProgress; tasks[taskId].dappContract = dappContract; tasks[taskId].blockNumber = blockNumber; // Emit the ComputeTask event which each node is watching for emit ComputeTask( dappContract, taskId, callable, callableArgs, callback, fee, preprocessors, blockNumber, true ); // Transferring before emitting does not work // TODO: check the allowance first engToken.transferFrom(msg.sender, this, fee); return ReturnValue.Ok; } // Verify the task results signature function verifyCommitSig(Task task, bytes data, bytes sig) internal returns (address) { // Recreating a data hash to validate the signature bytes memory code = GetCode2.at(task.dappContract); // Build a hash to validate that the I/Os are matching bytes32 hash = keccak256(abi.encodePacked(task.callableArgs, data, code)); // The worker address is not a real Ethereum wallet address but // one generated from its signing key address workerAddr = hash.recover(sig); emit ValidatedSig(sig, hash, workerAddr, true); return workerAddr; } // Execute the encoded function in the specified contract function executeCall(address to, uint256 value, bytes data) internal returns (bool success) { assembly { success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0) } } /** * Commit the computation task results on chain * * @param taskId The reference task id * @param data The encoded callback function call (which includes the computation results) * @param sig The data signed by the the worker's enclave * @param blockNumber The block number which originated the task */ function commitResults(bytes32 taskId, bytes data, bytes sig, uint256 blockNumber) public workerRegistered(msg.sender) returns (ReturnValue) { // Task must be solved only once require(tasks[taskId].status == TaskStatus.InProgress, "Illegal status, task must be in progress."); // TODO: run worker selection algo to validate right worker require(block.number > blockNumber, "Block number in the future."); address sigAddr = verifyCommitSig(tasks[taskId], data, sig); require(sigAddr != address(0), "Cannot verify this signature."); require(sigAddr == workers[msg.sender].signer, "Invalid signature."); // The contract must hold enough fund to distribute reward // TODO: validate that the reward matches the opcodes computed uint256 reward = tasks[taskId].reward; require(reward > 0, "Reward cannot be zero."); // Invoking the callback method of the original contract require(executeCall(tasks[taskId].dappContract, 0, data), "Unable to invoke the callback"); // Keep a trace of the task worker and proof tasks[taskId].worker = msg.sender; tasks[taskId].sig = sig; tasks[taskId].status = TaskStatus.Executed; // TODO: send directly to the worker's custodian instead // Put the reward in the worker's bank // He can withdraw later Worker storage worker = workers[msg.sender]; worker.balance = worker.balance.add(reward); emit CommitResults(tasks[taskId].dappContract, sigAddr, sig, reward, true); return ReturnValue.Ok; } // Verify the signature submitted while reparameterizing workers function verifyParamsSig(uint256 seed, bytes sig) internal pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(seed)); address signer = hash.recover(sig); return signer; } /** * Reparameterizing workers with a new seed * This should be called for each epoch by the Principal node * * @param seed The random integer generated by the enclave * @param sig The random integer signed by the the principal node's enclave */ function setWorkersParams(uint256 seed, bytes sig) public workerRegistered(msg.sender) returns (ReturnValue) { require(workers[msg.sender].signer == principal, "Only the Principal can update the seed"); address sigAddr = verifyParamsSig(seed, sig); require(sigAddr == principal, "Invalid signature"); // Create a new workers parameters item for the specified seed. // The workers parameters list is a sort of cache, it never grows beyond its limit. // If the list is full, the new item will replace the item assigned to the lowest block number. uint ti = 0; for (uint pi = 0; pi < workersParams.length; pi++) { // Find an empty slot in the array, if full use the lowest block number if (workersParams[pi].firstBlockNumber == 0) { ti = pi; break; } else if (workersParams[pi].firstBlockNumber < workersParams[ti].firstBlockNumber) { ti = pi; } } workersParams[ti].firstBlockNumber = block.number; workersParams[ti].seed = seed; // Copy the current worker list for (uint wi = 0; wi < workerAddresses.length; wi++) { if (workerAddresses[wi] != 0x0) { workersParams[ti].workerAddresses.length++; workersParams[ti].workerAddresses[wi] = workerAddresses[wi]; } } emit WorkersParameterized(seed, workerAddresses, true); return ReturnValue.Ok; } // The workers parameters nearest the specified block number function getWorkersParamsIndex(uint256 blockNumber) internal view returns (int8) { int8 ci = - 1; for (uint i = 0; i < workersParams.length; i++) { if (workersParams[i].firstBlockNumber <= blockNumber && (ci == - 1 || workersParams[i].firstBlockNumber > workersParams[uint(ci)].firstBlockNumber)) { ci = int8(i); } } return ci; } /** * The worker parameters corresponding to the specified block number * * @param blockNumber The reference block number */ function getWorkersParams(uint256 blockNumber) public view returns (uint256, uint256, address[]) { // The workers parameters for a given block number int8 idx = getWorkersParamsIndex(blockNumber); require(idx != - 1, "No workers parameters entry for specified block number"); uint index = uint(idx); WorkersParams memory _workerParams = workersParams[index]; address[] memory addrs = filterWorkers(_workerParams.workerAddresses); return (_workerParams.firstBlockNumber, _workerParams.seed, addrs); } // Filter out bad values from a list of worker addresses function filterWorkers(address[] addrs) internal view returns (address[]) { // TODO: I don't know why the list contains empty addresses, investigate uint cpt = 0; for (uint i = 0; i < addrs.length; i++) { if (addrs[i] != 0x0 && workers[addrs[i]].signer != principal) { cpt++; } } address[] memory _workers = new address[](cpt); uint cur = 0; for (uint iw = 0; iw < addrs.length; iw++) { if (addrs[iw] != 0x0 && workers[addrs[iw]].signer != principal) { _workers[cur] = addrs[iw]; cur++; } } return _workers; } /** * Apply pseudo-randomness to discover the selected worker for the specified task * * @param blockNumber The reference block number * @param taskId The reference task id */ function selectWorker(uint256 blockNumber, bytes32 taskId) public view returns (address) { (uint256 b, uint256 seed, address[] memory workerArray) = getWorkersParams(blockNumber); address[] memory _workers = filterWorkers(workerArray); bytes32 hash = keccak256(abi.encodePacked(seed, taskId)); uint256 index = uint256(hash) % _workers.length; return _workers[index]; } /** * The RLP encoded report returned by the IAS server * * @param custodian The worker's custodian address */ function getReport(address custodian) public view workerRegistered(custodian) returns (address, bytes) { // The RLP encoded report and signer's address for the specified worker require(workers[custodian].signer != 0x0, "Worker not registered"); return (workers[custodian].signer, workers[custodian].report); } }
A registry of all active and historical tasks with their attributes TODO: do we keep tasks forever? if not, when do we delete them?
mapping(bytes32 => Task) public tasks;
12,955,341
[ 1, 37, 4023, 434, 777, 2695, 471, 23922, 4592, 598, 3675, 1677, 2660, 30, 741, 732, 3455, 4592, 21238, 35, 309, 486, 16, 1347, 741, 732, 1430, 2182, 35, 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, 565, 2874, 12, 3890, 1578, 516, 3837, 13, 1071, 4592, 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 ]
// SPDX-License-Identifier: MIT /* * JuiceBox.sol * * Created: October 27, 2021 * * Price: FREE * Rinkeby: 0x09494437a042494eAdA9801A85eE494cFB27D75b * Mainnet: * * Description: An ERC-721 token that will be claimable by anyone who owns 'the Plug' * * - There will be 4 variations, each with a different rarity (based on how likely it is * to receive, i.e. v1:60%, v2:20%, v3:15%, v4:5%) * - Owners with multiple Plugs will benefit through a distribution scheme that shifts * the probability of minting each variation towards 25% */ pragma solidity >=0.5.16 <0.9.0; import "./Kasbeer721.sol"; //@title Juice Box //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd) contract JuiceBox is Kasbeer721 { // ------------- // EVENTS & VARS // ------------- event JuiceBoxMinted(uint256 indexed a); event JuiceBoxBurned(uint256 indexed a); //@dev This is how we'll keep track of who has already minted a JuiceBox mapping (address => bool) internal _boxHolders; //@dev Keep track of which token ID is associated with which hash mapping (uint256 => string) internal _tokenToHash; //@dev Initial production hashes string [NUM_ASSETS] boxHashes = ["QmbZH1NZLvUTqeaHXH37fVnb7QHcCFDsn4QKvicM1bmn5j", "QmVXiZFCwxBiJQJCpiSCKz8TkaWmnEBpT6stmxYqRK4FeY", "Qmds7Ag48sfeodwmtWmTokFGZoHiGZXYN2YbojtjTR7GhR", "QmeUPdEvAU5sSEv1Nwixbu1oxkSFCY194m8Drm9u3rtVWg"]; //cherry, berry, kiwi, lemon //@dev Associated weights of probability for hashes uint16 [NUM_ASSETS] boxWeights = [60, 23, 15, 2];//cherry, berry, kiwi, lemon //@dev Secret word to prevent etherscan claims string private _secret; constructor(string memory secret) Kasbeer721("Juice Box", "") { _whitelistActive = true; _secret = secret; _contractUri = "ipfs://QmdafigFsnSjondbSFKWhV2zbCf8qF5xEkgNoCYcnanhD6"; payoutAddress = 0x6b8C6E15818C74895c31A1C91390b3d42B336799;//logik } // ----------- // RESTRICTORS // ----------- modifier boxAvailable() { require(getCurrentId() < MAX_NUM_TOKENS, "JuiceBox: no JuiceBox's left to mint"); _; } modifier tokenExists(uint256 tokenId) { require(_exists(tokenId), "JuiceBox: nonexistent token"); _; } // --------------- // JUICE BOX MAGIC // --------------- //@dev Override 'tokenURI' to account for asset/hash cycling function tokenURI(uint256 tokenId) public view virtual override tokenExists(tokenId) returns (string memory) { return string(abi.encodePacked(_baseURI(), _tokenToHash[tokenId])); } //@dev Get the secret word function _getSecret() private view returns (string memory) { return _secret; } //// ---------------------- //// IPFS HASH MANIPULATION //// ---------------------- //@dev Get the hash stored at `idx` function getHashByIndex(uint8 idx) public view hashIndexInRange(idx) returns (string memory) { return boxHashes[idx]; } //@dev Allows us to update the IPFS hash values (one at a time) // 0:cherry, 1:berry, 2:kiwi, 3:lemon function updateHashForIndex(uint8 idx, string memory str) public isSquad hashIndexInRange(idx) { boxHashes[idx] = str; } // ------------------ // MINTING & CLAIMING // ------------------ //@dev Allows owners to mint for free function mint(address to) public virtual override isSquad boxAvailable returns (uint256 tid) { tid = _mintInternal(to); _assignHash(tid, 1); } //@dev Mint a specific juice box (owners only) function mintWithHash(address to, string memory hash) public isSquad returns (uint256 tid) { tid = _mintInternal(to); _tokenToHash[tid] = hash; } //@dev Claim a JuiceBox if you're a Plug holder function claim(address to, uint8 numPlugs, string memory secret) public boxAvailable whitelistEnabled onlyWhitelist(to) saleActive returns (uint256 tid, string memory hash) { require(!_boxHolders[to], "JuiceBox: cannot claim more than 1"); require(!_isContract(to), "JuiceBox: silly rabbit :P"); require(_stringsEqual(secret, _getSecret()), "JuiceBox: silly rabbit :P"); tid = _mintInternal(to); hash = _assignHash(tid, numPlugs); } //@dev Mints a single Juice Box & updates `_boxHolders` accordingly function _mintInternal(address to) internal virtual returns (uint256 newId) { _incrementTokenId(); newId = getCurrentId(); _safeMint(to, newId); _markAsClaimed(to); emit JuiceBoxMinted(newId); } //@dev Based on the number of Plugs owned by the sender, randomly select // a JuiceBox hash that will be associated with their token id function _assignHash(uint256 tid, uint8 numPlugs) private tokenExists(tid) returns (string memory hash) { uint8[] memory weights = new uint8[](NUM_ASSETS); //calculate new weights based on `numPlugs` if (numPlugs > 15) numPlugs = 15; weights[0] = uint8(boxWeights[0] - 35*((numPlugs-1)/10));//cherry: 60% -> 25% weights[1] = uint8(boxWeights[1] + 2*((numPlugs-1)/10));//berry: 23% -> 25% weights[2] = uint8(boxWeights[2] + 10*((numPlugs-1)/10));//kiwi: 15% -> 25% weights[3] = uint8(boxWeights[3] + 23*((numPlugs-1)/10));//lemon: 2% -> 25% uint16 rnd = random() % 100;//should be b/n 0 & 100 //randomly select a juice box hash uint8 i; for (i = 0; i < NUM_ASSETS; i++) { if (rnd < weights[i]) { hash = boxHashes[i]; break; } rnd -= weights[i]; } //assign the selected hash to this token id _tokenToHash[tid] = hash; } //@dev Update `_boxHolders` so that `a` cannot claim another juice box function _markAsClaimed(address a) private { _boxHolders[a] = true; } function getHashForTid(uint256 tid) public view tokenExists(tid) returns (string memory) { return _tokenToHash[tid]; } //@dev Pseudo-random number generator function random() public view returns (uint16 rnd) { return uint16(uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, boxWeights)))); } } // SPDX-License-Identifier: MIT /* * Kasbeer721.sol * * Created: October 27, 2021 * * Tuned-up ERC721 that covers a multitude of features that are generally useful * so that it can be easily extended for quick customization . */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./access/Whitelistable.sol"; import "./access/Pausable.sol"; import "./utils/LibPart.sol"; //@title Kasbeer721 - Beefed up ERC721 //@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, ig:overprivilegd) contract Kasbeer721 is ERC721, Whitelistable, Pausable { using SafeMath for uint256; using Counters for Counters.Counter; // ------------- // EVENTS & VARS // ------------- event Kasbeer721Minted(uint256 indexed tokenId); event Kasbeer721Burned(uint256 indexed tokenId); //@dev Token incrementing Counters.Counter internal _tokenIds; //@dev Important numbers uint constant NUM_ASSETS = 4;//4 juice box variations uint constant MAX_NUM_TOKENS = 111; //@dev Properties string internal _contractUri; address public payoutAddress; //@dev These are needed for contract compatability uint256 constant public royaltyFeeBps = 1000; // 10% bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a; bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca; constructor(string memory temp_name, string memory temp_symbol) ERC721(temp_name, temp_symbol) {} // --------- // MODIFIERS // --------- modifier hashIndexInRange(uint8 idx) { require(0 <= idx && idx < NUM_ASSETS, "Kasbeer721: index OOB"); _; } modifier onlyValidTokenId(uint256 tokenId) { require(1 <= tokenId && tokenId <= MAX_NUM_TOKENS, "Kasbeer721: tokenId OOB"); _; } // ---------- // MAIN LOGIC // ---------- //@dev All of the asset's will be pinned to IPFS function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } //@dev This is here as a reminder to override for custom transfer functionality function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); } //@dev Allows owners to mint for free function mint(address to) public virtual isSquad returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); emit Kasbeer721Minted(newId); return newId; } //@dev Custom burn function - nothing special function burn(uint256 tokenId) public virtual { require( isInSquad(_msgSender()) || _msgSender() == ownerOf(tokenId), "Kasbeer721: not owner or in squad." ); _burn(tokenId); emit Kasbeer721Burned(tokenId); } //// -------- //// CONTRACT //// -------- //@dev Controls the contract-level metadata to include things like royalties function contractURI() public view returns(string memory) { return _contractUri; } //@dev Ability to change the contract URI function updateContractUri(string memory updatedContractUri) public isSquad { _contractUri = updatedContractUri; } //@dev Allows us to withdraw funds collected function withdraw(address payable wallet, uint256 amount) public isSquad { require(amount <= address(this).balance, "Kasbeer721: Insufficient funds to withdraw"); wallet.transfer(amount); } //@dev Destroy contract and reclaim leftover funds function kill() public onlyOwner { selfdestruct(payable(_msgSender())); } // ------- // HELPERS // ------- //@dev Returns the current token id (number minted so far) function getCurrentId() public view returns (uint256) { return _tokenIds.current(); } //@dev Increments `_tokenIds` by 1 function _incrementTokenId() internal { _tokenIds.increment(); } //@dev Determine if two strings are equal using the length + hash method function _stringsEqual(string memory a, string memory b) internal pure returns (bool) { bytes memory A = bytes(a); bytes memory B = bytes(b); if (A.length != B.length) { return false; } else { return keccak256(A) == keccak256(B); } } //@dev Determine if an address is a smart contract function _isContract(address a) internal view returns (bool) { uint32 size; assembly { size := extcodesize(a) } return size > 0; } // ----------------- // SECONDARY MARKETS // ----------------- //@dev Rarible Royalties V2 function getRaribleV2Royalties(uint256 id) onlyValidTokenId(id) external view returns (LibPart.Part[] memory) { LibPart.Part[] memory royalties = new LibPart.Part[](1); royalties[0] = LibPart.Part({ account: payable(payoutAddress), value: uint96(royaltyFeeBps) }); return royalties; } //@dev EIP-2981 function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) { uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000); return (payoutAddress, ourCut); } // ----------------- // INTERFACE SUPPORT // ----------------- //@dev Confirm that this contract is compatible w/ these interfaces function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACE_ID_ERC165 || interfaceId == _INTERFACE_ID_ROYALTIES || interfaceId == _INTERFACE_ID_ERC721 || interfaceId == _INTERFACE_ID_ERC721_METADATA || interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE || interfaceId == _INTERFACE_ID_EIP2981 || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT /* * Whitelistable.sol * * Created: December 21, 2021 * * Provides functionality for a "whitelist"/"guestlist" for inheriting contracts. */ pragma solidity >=0.5.16 <0.9.0; import "./SquadOwnable.sol"; //@title Whitelistable //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd) contract Whitelistable is SquadOwnable { // ------------- // EVENTS & VARS // ------------- event WhitelistActivated(address indexed a); event WhitelistDeactivated(address indexed a); //@dev Whitelist mapping for client addresses mapping (address => bool) internal _whitelist; //@dev Whitelist flag for active/inactive states bool internal _whitelistActive; constructor() { _whitelistActive = false; //add myself and then logik (client) _whitelist[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true; _whitelist[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true; } // --------- // MODIFIERS // --------- //@dev Determine if someone is in the whitelsit modifier onlyWhitelist(address a) { require(isWhitelisted(a), "Whitelistable: must be on whitelist"); _; } //@dev Prevent non-whitelist minting functions from being used modifier whitelistDisabled() { require(_whitelistActive == false, "Whitelistable: whitelist still active"); _; } //@dev Require that the whitelist is currently enabled modifier whitelistEnabled() { require(_whitelistActive == true, "Whitelistable: whitelist not active"); _; } // ---------- // MAIN LOGIC // ---------- //@dev Toggle the state of the whitelist (on/off) function toggleWhitelist() public isSquad { _whitelistActive = !_whitelistActive; if (_whitelistActive) { emit WhitelistActivated(_msgSender()); } else { emit WhitelistDeactivated(_msgSender()); } } //@dev Determine if `a` is in the `_whitelist function isWhitelisted(address a) public view returns (bool) { return _whitelist[a]; } //// ---------- //// ADD/REMOVE //// ---------- //@dev Add a single address to whitelist function addToWhitelist(address a) public isSquad { require(!isWhitelisted(a), "Whitelistable: already whitelisted"); _whitelist[a] = true; } //@dev Remove a single address from the whitelist function removeFromWhitelist(address a) public isSquad { require(isWhitelisted(a), "Whitelistable: not in whitelist"); _whitelist[a] = false; } //@dev Add a list of addresses to the whitelist function bulkAddToWhitelist(address[] memory addresses) public isSquad { uint addrLen = addresses.length; require(addrLen > 1, "Whitelistable: use `addToWhitelist` instead"); require(addrLen < 65536, "Whitelistable: cannot add more than 65535 at once"); uint16 i; for (i = 0; i < addrLen; i++) { if (!isWhitelisted(addresses[i])) { _whitelist[addresses[i]] = true; } } } } // SPDX-License-Identifier: MIT /* * Pausable.sol * * Created: December 21, 2021 * * Provides functionality for pausing and unpausing the sale (or other functionality) */ pragma solidity >=0.5.16 <0.9.0; import "./SquadOwnable.sol"; //@title Pausable //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd) contract Pausable is SquadOwnable { // ------------- // EVENTS & VARS // ------------- event Paused(address indexed a); event Unpaused(address indexed a); bool private _paused; constructor() { _paused = false; } // --------- // MODIFIERS // --------- //@dev This will require the sale to be unpaused modifier saleActive() { require(!_paused, "Pausable: sale paused."); _; } // ---------- // MAIN LOGIC // ---------- //@dev Pause or unpause minting function toggleSaleActive() public isSquad { _paused = !_paused; if (_paused) { emit Paused(_msgSender()); } else { emit Unpaused(_msgSender()); } } //@dev Determine if the sale is currently paused function paused() public view virtual returns (bool) { return _paused; } } // SPDX-License-Identifier: MIT /* * LibPart.sol * * Author: Jack Kasbeer (taken from 'dot') * Created: October 20, 2021 */ pragma solidity >=0.5.16 <0.9.0; //@dev We need this libary for Rarible library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT /* * SquadOwnable.sol * * Created: December 21, 2021 * * An extension of `Ownable.sol` to accomodate for a potential list of owners. * NOTE: this will need to be the last inherited contract to give all parents * access to the modifiers it provides */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; //@title SquadOwnable //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd) contract SquadOwnable is Ownable { //@dev Ownership - list of squad members (owners) mapping (address => bool) internal _squad; constructor() { //add myself and then logik (client) _squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true; _squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true; } //@dev Custom modifier for multiple owners modifier isSquad() { require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad."); _; } //@dev Determine if address `a` is an approved owner function isInSquad(address a) public view returns (bool) { return _squad[a]; } //@dev Add `a` to the squad function addToSquad(address a) public onlyOwner { require(!isInSquad(a), "SquadOwnable: Address already in squad."); _squad[a] = true; } //@dev Remove `a` from the squad function removeFromSquad(address a) public onlyOwner { require(isInSquad(a), "SquadOwnable: Address already not in squad."); _squad[a] = false; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
@dev Determine if `a` is in the `_whitelist
function isWhitelisted(address a) public view returns (bool) { return _whitelist[a]; }
6,133,009
[ 1, 8519, 309, 1375, 69, 68, 353, 316, 326, 1375, 67, 20409, 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, 353, 18927, 329, 12, 2867, 279, 13, 1071, 1476, 1135, 261, 6430, 13, 203, 202, 95, 203, 202, 202, 2463, 389, 20409, 63, 69, 15533, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB3fE31F720F1832966e5603432c7e0437f724aff/sources/contracts/PresaleV2.sol
* @dev To calculate the price in USD for given amount of tokens. @param _amount No of tokens/
function calculatePrice(uint256 _amount) internal view returns (uint256 totalValue) { uint256 USDTAmount; require(_amount <= maxTokensToBuy, "Amount exceeds max tokens to buy"); if (_amount + totalTokensSold > token_amount[currentStep]) { require(currentStep < 2, "Insufficient token amount."); uint256 tokenAmountForCurrentPrice = token_amount[currentStep] - totalTokensSold; USDTAmount = tokenAmountForCurrentPrice * token_price[currentStep] + (_amount - tokenAmountForCurrentPrice) * token_price[currentStep + 1]; } else USDTAmount = _amount * token_price[currentStep]; return USDTAmount; }
8,439,416
[ 1, 774, 4604, 326, 6205, 316, 587, 9903, 364, 864, 3844, 434, 2430, 18, 225, 389, 8949, 2631, 434, 2430, 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 ]
[ 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, 565, 445, 4604, 5147, 12, 11890, 5034, 389, 8949, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 2078, 620, 13, 203, 565, 288, 203, 3639, 2254, 5034, 11836, 9081, 6275, 31, 203, 3639, 2583, 24899, 8949, 1648, 943, 5157, 774, 38, 9835, 16, 315, 6275, 14399, 943, 2430, 358, 30143, 8863, 203, 3639, 309, 261, 67, 8949, 397, 2078, 5157, 55, 1673, 405, 1147, 67, 8949, 63, 2972, 4160, 5717, 288, 203, 5411, 2583, 12, 2972, 4160, 411, 576, 16, 315, 5048, 11339, 1147, 3844, 1199, 1769, 203, 5411, 2254, 5034, 1147, 6275, 1290, 3935, 5147, 273, 1147, 67, 8949, 63, 2972, 4160, 65, 300, 203, 7734, 2078, 5157, 55, 1673, 31, 203, 5411, 11836, 9081, 6275, 273, 203, 7734, 1147, 6275, 1290, 3935, 5147, 380, 203, 7734, 1147, 67, 8694, 63, 2972, 4160, 65, 397, 203, 7734, 261, 67, 8949, 300, 1147, 6275, 1290, 3935, 5147, 13, 380, 203, 7734, 1147, 67, 8694, 63, 2972, 4160, 397, 404, 15533, 203, 3639, 289, 469, 11836, 9081, 6275, 273, 389, 8949, 380, 1147, 67, 8694, 63, 2972, 4160, 15533, 203, 3639, 327, 11836, 9081, 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 ]
./partial_match/1/0xFa2B9E5f4b60767D4C3ca6e316d8599311419B3e/sources/ParadiseToken.sol
Compute the number of tokens to be rewarded to the sender Note: it's important for this calculation that both wei and PDT have the same number of decimal places (18) Transfer the tokens from the crowdsale supply to the sender update the total amount raised update the sender's balance of wei contributed Check if the funding goal or cap have been reached
function buy () payable public whenNotPaused beforeDeadline afterStartTime saleNotClosed { require(msg.value >= minContribution); uint amount = msg.value; uint numTokens = amount.mul(rate); if (tokenReward.transferFrom(tokenReward.owner(), msg.sender, numTokens)) { amountRaised = amountRaised.add(amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); emit FundTransfer(msg.sender, amount, true); checkFundingGoal(); checkFundingCap(); } else { revert(); } }
2,839,414
[ 1, 7018, 326, 1300, 434, 2430, 358, 506, 283, 11804, 358, 326, 5793, 3609, 30, 518, 1807, 10802, 364, 333, 11096, 716, 3937, 732, 77, 471, 453, 9081, 1240, 326, 1967, 1300, 434, 6970, 12576, 261, 2643, 13, 12279, 326, 2430, 628, 326, 276, 492, 2377, 5349, 14467, 358, 326, 5793, 1089, 326, 2078, 3844, 11531, 1089, 326, 5793, 1807, 11013, 434, 732, 77, 356, 11050, 2073, 309, 326, 22058, 17683, 578, 3523, 1240, 2118, 8675, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 1832, 203, 3639, 8843, 429, 1071, 203, 3639, 1347, 1248, 28590, 203, 3639, 1865, 15839, 203, 3639, 1839, 13649, 203, 3639, 272, 5349, 1248, 7395, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 1131, 442, 4027, 1769, 203, 3639, 2254, 3844, 273, 1234, 18, 1132, 31, 203, 540, 203, 3639, 2254, 818, 5157, 273, 3844, 18, 16411, 12, 5141, 1769, 203, 540, 203, 3639, 309, 261, 2316, 17631, 1060, 18, 13866, 1265, 12, 2316, 17631, 1060, 18, 8443, 9334, 1234, 18, 15330, 16, 818, 5157, 3719, 288, 203, 377, 203, 3639, 3844, 12649, 5918, 273, 3844, 12649, 5918, 18, 1289, 12, 8949, 1769, 203, 1377, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 8009, 1289, 12, 8949, 1769, 203, 203, 3639, 3626, 478, 1074, 5912, 12, 3576, 18, 15330, 16, 3844, 16, 638, 1769, 203, 3639, 866, 42, 14351, 27716, 5621, 203, 3639, 866, 42, 14351, 4664, 5621, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 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 ]
./full_match/77/0xe7515f8DBb2545772C0F60ce14Bd117D6847eb4d/sources/contracts/MuliTokenForwardingRulesManager.sol
* Updates the forwarding rule for bridging specific token. Only owner can call this method. @param _token address of the token contract on the foreign side. @param _enable true, if bridge operations for a given token should be forwarded to the oracle-driven lane./
function setTokenForwardingRule(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(1) : int256(0)); }
5,049,456
[ 1, 5121, 326, 20635, 1720, 364, 324, 1691, 1998, 2923, 1147, 18, 5098, 3410, 848, 745, 333, 707, 18, 225, 389, 2316, 1758, 434, 326, 1147, 6835, 603, 326, 5523, 4889, 18, 225, 389, 7589, 638, 16, 309, 10105, 5295, 364, 279, 864, 1147, 1410, 506, 19683, 358, 326, 20865, 17, 3069, 837, 328, 8806, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 22629, 21487, 2175, 12, 2867, 389, 2316, 16, 1426, 389, 7589, 13, 3903, 288, 203, 3639, 2583, 24899, 2316, 480, 16743, 67, 15140, 1769, 203, 3639, 389, 542, 21487, 2175, 24899, 2316, 16, 16743, 67, 15140, 16, 16743, 67, 15140, 16, 389, 7589, 692, 509, 5034, 12, 21, 13, 294, 509, 5034, 12, 20, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x74C3bAD428Ed6511Da87DF578d6577D5a75392eF/sources/KunlunToken.sol
Base class of token-owner
contract Ownable { function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } @newOwner: address of newOwner function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } function kill() onlyOwner public{ selfdestruct(owner); } }
15,568,707
[ 1, 2171, 667, 434, 1147, 17, 8443, 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, 16351, 14223, 6914, 288, 203, 203, 202, 915, 14223, 6914, 1435, 1071, 7010, 202, 95, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 5541, 1435, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 202, 202, 67, 31, 203, 202, 97, 203, 1082, 202, 36, 2704, 5541, 30, 202, 2867, 434, 394, 5541, 203, 202, 915, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 95, 203, 202, 202, 430, 261, 2704, 5541, 480, 1758, 12, 20, 3719, 288, 203, 202, 202, 8443, 273, 394, 5541, 31, 203, 202, 202, 97, 203, 202, 97, 203, 202, 203, 202, 915, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 95, 203, 202, 202, 430, 261, 2704, 5541, 480, 1758, 12, 20, 3719, 288, 203, 202, 202, 8443, 273, 394, 5541, 31, 203, 202, 202, 97, 203, 202, 97, 203, 202, 203, 202, 915, 8673, 1435, 1338, 5541, 1071, 95, 203, 202, 202, 2890, 5489, 8813, 12, 8443, 1769, 203, 202, 97, 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 ]
// 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]; } }
@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); }
1,697,533
[ 1, 2276, 358, 444, 326, 1375, 546, 3477, 72, 17711, 68, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1001, 542, 41, 451, 3477, 72, 17711, 12, 2867, 389, 4285, 41, 451, 3477, 72, 17711, 13, 3238, 288, 203, 3639, 1758, 2807, 41, 451, 3477, 72, 17711, 273, 13750, 3477, 72, 17711, 31, 203, 3639, 2583, 12, 203, 5411, 389, 4285, 41, 451, 3477, 72, 17711, 480, 2807, 41, 451, 3477, 72, 17711, 16, 203, 5411, 10425, 542, 41, 451, 3477, 72, 17711, 30, 1445, 1818, 444, 6, 203, 3639, 11272, 203, 203, 3639, 1001, 5662, 17711, 24899, 4285, 41, 451, 3477, 72, 17711, 1769, 203, 203, 3639, 13750, 3477, 72, 17711, 273, 389, 4285, 41, 451, 3477, 72, 17711, 31, 203, 203, 3639, 3626, 512, 451, 3477, 72, 17711, 694, 12, 10001, 41, 451, 3477, 72, 17711, 16, 389, 4285, 41, 451, 3477, 72, 17711, 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 ]
./full_match/7001/0x40aF9F5720d7C573d06F9D2003Aa1d7dD60eD97B/sources/contracts/userContract.bitsave.sol
import "@zetachain/zevm-example-contracts/contracts/shared/SwapHelperLib.sol";
import "./utils/BitsaveHelperLib.sol";
13,228,856
[ 1, 5666, 8787, 94, 278, 497, 530, 19, 8489, 3489, 17, 8236, 17, 16351, 87, 19, 16351, 87, 19, 11574, 19, 12521, 2276, 5664, 18, 18281, 14432, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 5666, 25165, 5471, 19, 6495, 836, 2276, 5664, 18, 18281, 14432, 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 ]
/** * SPDX-License-Identifier: MIT **/ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./FieldFacet/Dibbler.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @author Publius * @title Budget Facet **/ contract BudgetFacet is Dibbler { using SafeMath for uint256; function budgetSow(uint256 amount) public returns (uint256) { require(isBudget(msg.sender), "Budget: sender must be budget."); bean().burnFrom(msg.sender, amount); decreaseSoil(amount); return _sowNoSoil(amount, msg.sender); } function isBudget(address account) public view returns (bool) { return s.isBudget[account]; } function decreaseSoil(uint256 amount) private { uint256 soil = s.f.soil; if (soil > amount) s.f.soil = soil.sub(amount); else if (soil > 0) s.f.soil = 0; } } /** * SPDX-License-Identifier: MIT **/ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "../../../C.sol"; import "../../../interfaces/IBean.sol"; import "../../../libraries/Decimal.sol"; import "../../../libraries/LibCheck.sol"; /** * @author Publius * @title Dibbler **/ contract Dibbler { using SafeMath for uint256; using SafeMath for uint32; using Decimal for Decimal.D256; AppStorage internal s; uint32 private constant MAX_UINT32 = 2**32-1; event Sow(address indexed account, uint256 index, uint256 beans, uint256 pods); /** * Shed **/ function _sow(uint256 amount, address account) internal returns (uint256) { require(amount > 0, "Field: Must purchase non-zero amount."); s.f.soil = s.f.soil.sub(amount, "Field: Not enough outstanding Soil."); uint256 pods = beansToPods(amount, s.w.yield); sowPlot(account, amount, pods); s.f.pods = s.f.pods.add(pods); saveSowTime(); return pods; } function _sowNoSoil(uint256 amount, address account) internal returns (uint256) { require(amount > 0, "Field: Must purchase non-zero amount."); uint256 pods = beansToPods(amount, s.w.yield); sowPlot(account, amount, pods); s.f.pods = s.f.pods.add(pods); saveSowTime(); return pods; } function sowPlot(address account, uint256 beans, uint256 pods) internal { s.a[account].field.plots[s.f.pods] = pods; emit Sow(account, s.f.pods, beans, pods); } function beansToPods(uint256 beanstalks, uint256 y) internal pure returns (uint256) { Decimal.D256 memory rate = Decimal.ratio(y, 100).add(Decimal.one()); return Decimal.from(beanstalks).mul(rate).asUint256(); } function bean() internal view returns (IBean) { return IBean(s.c.bean); } function saveSowTime() private { uint256 totalBeanSupply = bean().totalSupply(); if (s.f.soil >= totalBeanSupply.div(C.getComplexWeatherDenominator())) return; uint256 sowTime = block.timestamp.sub(s.season.timestamp); s.w.nextSowTime = uint32(sowTime); uint96 soilPercent = uint96(s.f.soil.mul(1e18).div(totalBeanSupply)); if (!s.w.didSowBelowMin) s.w.didSowBelowMin = true; if ( soilPercent <= C.getUpperBoundPodRate().mul(s.w.lastSoilPercent).asUint256() && !s.w.didSowFaster && s.w.lastSowTime != MAX_UINT32 && s.w.lastDSoil != 0 ) { uint256 deltaSoil = s.w.startSoil.sub(s.f.soil); if (Decimal.ratio(deltaSoil, s.w.lastDSoil).greaterThan(C.getLowerBoundDPD())) { uint256 fasterTime = s.w.lastSowTime > C.getSteadySowTime() ? s.w.lastSowTime.sub(C.getSteadySowTime()) : 0; if (sowTime < fasterTime) s.w.didSowFaster = true; else s.w.lastSowTime = MAX_UINT32; } } } } // 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.7.6; pragma experimental ABIEncoderV2; import "./libraries/Decimal.sol"; /** * @author Publius * @title C holds the contracts for Beanstalk. **/ library C { using Decimal for Decimal.D256; using SafeMath for uint256; // Chain uint256 private constant CHAIN_ID = 1; // Mainnet // Season uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour // Sun uint256 private constant HARVESET_PERCENTAGE = 5e17; // 50% // Weather uint256 private constant POD_RATE_LOWER_BOUND = 5e16; // 5% uint256 private constant OPTIMAL_POD_RATE = 15e16; // 15% uint256 private constant POD_RATE_UPPER_BOUND = 25e16; // 25% uint256 private constant DELTA_POD_DEMAND_LOWER_BOUND = 95e16; // 95% uint256 private constant DELTA_POD_DEMAND_UPPER_BOUND = 105e16; // 105% uint256 private constant STEADY_SOW_TIME = 60; // 1 minute uint256 private constant RAIN_TIME = 24; // 24 seasons = 1 day // Governance uint32 private constant GOVERNANCE_PERIOD = 168; // 168 seasons = 7 days uint32 private constant GOVERNANCE_EMERGENCY_PERIOD = 86400; // 1 day uint256 private constant GOVERNANCE_PASS_THRESHOLD = 5e17; // 1/2 uint256 private constant GOVERNANCE_EMERGENCY_THRESHOLD_NUMERATOR = 2; // 2/3 uint256 private constant GOVERNANCE_EMERGENCY_THRESHOLD_DEMONINATOR = 3; // 2/3 uint32 private constant GOVERNANCE_EXPIRATION = 24; // 24 seasons = 1 day uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 1e15; // 0.1% uint256 private constant BASE_COMMIT_INCENTIVE = 1e8; // 100 beans uint256 private constant MAX_PROPOSITIONS = 5; // Silo uint256 private constant BASE_ADVANCE_INCENTIVE = 1e8; // 100 beans uint32 private constant WITHDRAW_TIME = 25; // 24 + 1 seasons uint256 private constant SEEDS_PER_BEAN = 2; uint256 private constant SEEDS_PER_LP_BEAN = 4; uint256 private constant STALK_PER_BEAN = 10000; uint256 private constant ROOTS_BASE = 1e12; // Field uint256 private constant MAX_SOIL_DENOMINATOR = 4; // 25% uint256 private constant COMPLEX_WEATHER_DENOMINATOR = 1000; // 0.1% /** * Getters **/ function getSeasonPeriod() internal pure returns (uint256) { return CURRENT_SEASON_PERIOD; } function getGovernancePeriod() internal pure returns (uint32) { return GOVERNANCE_PERIOD; } function getGovernanceEmergencyPeriod() internal pure returns (uint32) { return GOVERNANCE_EMERGENCY_PERIOD; } function getGovernanceExpiration() internal pure returns (uint256) { return GOVERNANCE_EXPIRATION; } function getGovernancePassThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_PASS_THRESHOLD}); } function getGovernanceEmergencyThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(GOVERNANCE_EMERGENCY_THRESHOLD_NUMERATOR,GOVERNANCE_EMERGENCY_THRESHOLD_DEMONINATOR); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_PROPOSAL_THRESHOLD}); } function getAdvanceIncentive() internal pure returns (uint256) { return BASE_ADVANCE_INCENTIVE; } function getCommitIncentive() internal pure returns (uint256) { return BASE_COMMIT_INCENTIVE; } function getSiloWithdrawSeasons() internal pure returns (uint32) { return WITHDRAW_TIME; } function getComplexWeatherDenominator() internal pure returns (uint256) { return COMPLEX_WEATHER_DENOMINATOR; } function getMaxSoilDenominator() internal pure returns (uint256) { return MAX_SOIL_DENOMINATOR; } function getHarvestPercentage() internal pure returns (uint256) { return HARVESET_PERCENTAGE; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getOptimalPodRate() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(OPTIMAL_POD_RATE,1e18); } function getUpperBoundPodRate() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(POD_RATE_UPPER_BOUND,1e18); } function getLowerBoundPodRate() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(POD_RATE_LOWER_BOUND,1e18); } function getUpperBoundDPD() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(DELTA_POD_DEMAND_UPPER_BOUND,1e18); } function getLowerBoundDPD() internal pure returns (Decimal.D256 memory) { return Decimal.ratio(DELTA_POD_DEMAND_LOWER_BOUND,1e18); } function getSteadySowTime() internal pure returns (uint256) { return STEADY_SOW_TIME; } function getRainTime() internal pure returns (uint256) { return RAIN_TIME; } function getMaxPropositions() internal pure returns (uint256) { return MAX_PROPOSITIONS; } function getSeedsPerBean() internal pure returns (uint256) { return SEEDS_PER_BEAN; } function getSeedsPerLPBean() internal pure returns (uint256) { return SEEDS_PER_LP_BEAN; } function getStalkPerBean() internal pure returns (uint256) { return STALK_PER_BEAN; } function getStalkPerLPSeed() internal pure returns (uint256) { return STALK_PER_BEAN/SEEDS_PER_LP_BEAN; } function getRootsBase() internal pure returns (uint256) { return ROOTS_BASE; } } /** * SPDX-License-Identifier: MIT **/ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @author Publius * @title Bean Interface **/ abstract contract IBean is IERC20 { function burn(uint256 amount) public virtual; function burnFrom(address account, uint256 amount) public virtual; function mint(address account, uint256 amount) public virtual returns (bool); } /* SPDX-License-Identifier: MIT */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* SPDX-License-Identifier: MIT */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./LibAppStorage.sol"; import "../interfaces/IBean.sol"; /** * @author Publius * @title Check Library verifies Beanstalk's balances are correct. **/ library LibCheck { using SafeMath for uint256; function beanBalanceCheck() internal view { AppStorage storage s = LibAppStorage.diamondStorage(); require( IBean(s.c.bean).balanceOf(address(this)) >= s.f.harvestable.sub(s.f.harvested).add(s.bean.deposited).add(s.bean.withdrawn), "Check: Bean balance fail." ); } function lpBalanceCheck() internal view { AppStorage storage s = LibAppStorage.diamondStorage(); require( IUniswapV2Pair(s.c.pair).balanceOf(address(this)) >= s.lp.deposited.add(s.lp.withdrawn), "Check: LP balance fail." ); } function balanceCheck() internal view { AppStorage storage s = LibAppStorage.diamondStorage(); require( IBean(s.c.bean).balanceOf(address(this)) >= s.f.harvestable.sub(s.f.harvested).add(s.bean.deposited).add(s.bean.withdrawn), "Check: Bean balance fail." ); require( IUniswapV2Pair(s.c.pair).balanceOf(address(this)) >= s.lp.deposited.add(s.lp.withdrawn), "Check: LP balance fail." ); } } // 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; } } pragma solidity >=0.5.0; 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; } /* SPDX-License-Identifier: MIT */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "../farm/AppStorage.sol"; /** * @author Publius * @title App Storage Library allows libaries to access Beanstalk's state. **/ library LibAppStorage { function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } } } /* SPDX-License-Identifier: MIT */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/IDiamondCut.sol"; /** * @author Publius * @title App Storage defines the state object for Beanstalk. **/ contract Account { struct Field { mapping(uint256 => uint256) plots; mapping(address => uint256) podAllowances; } struct AssetSilo { mapping(uint32 => uint256) withdrawals; mapping(uint32 => uint256) deposits; mapping(uint32 => uint256) depositSeeds; } struct Silo { uint256 stalk; uint256 seeds; } struct SeasonOfPlenty { uint256 base; uint256 roots; uint256 basePerRoot; } struct State { Field field; AssetSilo bean; AssetSilo lp; Silo s; uint32 lockedUntil; uint32 lastUpdate; uint32 lastSop; uint32 lastRain; uint32 lastSIs; SeasonOfPlenty sop; uint256 roots; } } contract Storage { struct Contracts { address bean; address pair; address pegPair; address weth; } // Field struct Field { uint256 soil; uint256 pods; uint256 harvested; uint256 harvestable; } // Governance struct Bip { address proposer; uint32 start; uint32 period; bool executed; int pauseOrUnpause; uint128 timestamp; uint256 roots; uint256 endTotalRoots; } struct DiamondCut { IDiamondCut.FacetCut[] diamondCut; address initAddress; bytes initData; } struct Governance { uint32[] activeBips; uint32 bipIndex; mapping(uint32 => DiamondCut) diamondCuts; mapping(uint32 => mapping(address => bool)) voted; mapping(uint32 => Bip) bips; } // Silo struct AssetSilo { uint256 deposited; uint256 withdrawn; } struct IncreaseSilo { uint256 beans; uint256 stalk; } struct V1IncreaseSilo { uint256 beans; uint256 stalk; uint256 roots; } struct SeasonOfPlenty { uint256 weth; uint256 base; uint32 last; } struct Silo { uint256 stalk; uint256 seeds; uint256 roots; } // Season struct Oracle { bool initialized; uint256 cumulative; uint256 pegCumulative; uint32 timestamp; uint32 pegTimestamp; } struct Rain { uint32 start; bool raining; uint256 pods; uint256 roots; } struct Season { uint32 current; uint32 sis; uint256 start; uint256 period; uint256 timestamp; } struct Weather { uint256 startSoil; uint256 lastDSoil; uint96 lastSoilPercent; uint32 lastSowTime; uint32 nextSowTime; uint32 yield; bool didSowBelowMin; bool didSowFaster; } struct Fundraiser { address payee; address token; uint256 total; uint256 remaining; } } struct AppStorage { uint8 index; int8[32] cases; bool paused; uint128 pausedAt; Storage.Season season; Storage.Contracts c; Storage.Field f; Storage.Governance g; Storage.Oracle o; Storage.Rain r; Storage.Silo s; uint256 depreciated1; Storage.Weather w; Storage.AssetSilo bean; Storage.AssetSilo lp; Storage.IncreaseSilo si; Storage.SeasonOfPlenty sop; Storage.V1IncreaseSilo v1SI; uint256 unclaimedRoots; uint256 v2SIBeans; mapping (uint32 => uint256) sops; mapping (address => Account.State) a; uint32 bip0Start; uint32 hotFix3Start; mapping (uint32 => Storage.Fundraiser) fundraisers; uint32 fundraiserIndex; mapping (address => bool) isBudget; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.7.6; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); }
* @author Publius @title App Storage defines the state object for Beanstalk./
contract Account { SPDX-License-Identifier: MIT struct Field { mapping(uint256 => uint256) plots; mapping(address => uint256) podAllowances; } struct AssetSilo { mapping(uint32 => uint256) withdrawals; mapping(uint32 => uint256) deposits; mapping(uint32 => uint256) depositSeeds; } struct Silo { uint256 stalk; uint256 seeds; } struct SeasonOfPlenty { uint256 base; uint256 roots; uint256 basePerRoot; } struct State { Field field; AssetSilo bean; AssetSilo lp; Silo s; uint32 lockedUntil; uint32 lastUpdate; uint32 lastSop; uint32 lastRain; uint32 lastSIs; SeasonOfPlenty sop; uint256 roots; } }
173,777
[ 1, 52, 440, 8384, 225, 4677, 5235, 11164, 326, 919, 733, 364, 7704, 20852, 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 ]
[ 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, 16351, 6590, 288, 203, 203, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 203, 203, 565, 1958, 2286, 288, 203, 3639, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 17931, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 3713, 7009, 6872, 31, 203, 565, 289, 203, 203, 565, 1958, 10494, 19740, 83, 288, 203, 3639, 2874, 12, 11890, 1578, 516, 2254, 5034, 13, 598, 9446, 1031, 31, 203, 3639, 2874, 12, 11890, 1578, 516, 2254, 5034, 13, 443, 917, 1282, 31, 203, 3639, 2874, 12, 11890, 1578, 516, 2254, 5034, 13, 443, 1724, 1761, 9765, 31, 203, 565, 289, 203, 203, 565, 1958, 348, 31703, 288, 203, 3639, 2254, 5034, 384, 2960, 31, 203, 3639, 2254, 5034, 19076, 31, 203, 565, 289, 203, 203, 565, 1958, 3265, 2753, 951, 1749, 319, 93, 288, 203, 3639, 2254, 5034, 1026, 31, 203, 3639, 2254, 5034, 12876, 31, 203, 3639, 2254, 5034, 1026, 2173, 2375, 31, 203, 565, 289, 203, 203, 565, 1958, 3287, 288, 203, 3639, 2286, 652, 31, 203, 3639, 10494, 19740, 83, 3931, 31, 203, 3639, 10494, 19740, 83, 12423, 31, 203, 3639, 348, 31703, 272, 31, 203, 3639, 2254, 1578, 8586, 9716, 31, 203, 3639, 2254, 1578, 1142, 1891, 31, 203, 3639, 2254, 1578, 1142, 55, 556, 31, 203, 3639, 2254, 1578, 1142, 54, 530, 31, 203, 3639, 2254, 1578, 1142, 2320, 87, 31, 203, 3639, 3265, 2753, 951, 1749, 319, 93, 272, 556, 31, 203, 3639, 2254, 5034, 12876, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100 ]
// 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: 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 IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) 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 IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // 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 IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) 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 "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(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 "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) 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; /// @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 _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, 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; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official fees only. /// Fees can only be added upon fund setup, migration, or reconfiguration. contract FeeManager is IFeeManager, ExtensionBase, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using SafeMath for uint256; event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); 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, address indexed payee, uint256 sharesDue ); mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public ExtensionBase(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory enabledFees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(comptrollerProxy, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev There will be no fees if the caller is not a valid ComptrollerProxy function deactivateForFund() external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); // Force payout of remaining shares outstanding address[] memory fees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < fees.length; i++) { __payoutSharesOutstanding(comptrollerProxy, vaultProxy, fees[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); } /// @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 _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data /// @dev 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( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); (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++) { // Set fund config on fee IFee(fees[i]).addFundSettings(_comptrollerProxy, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[_comptrollerProxy].push(fees[i]); emit FeeEnabledForFund(_comptrollerProxy, fees[i], settingsData[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary(address _comptrollerProxy, uint256 _gavOrZero) private returns (uint256 gav_) { if (_gavOrZero == 0) { return IComptroller(_comptrollerProxy).calcGav(); } else { return _gavOrZero; } } /// @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 = getEnabledFeesForFund(_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 get the end recipient for a given fee and fund function __parseFeeRecipientForFund( address _comptrollerProxy, address _vaultProxy, address _fee ) private view returns (address recipient_) { recipient_ = IFee(_fee).getRecipientForFund(_comptrollerProxy); if (recipient_ == address(0)) { recipient_ = IVault(_vaultProxy).getOwner(); } return recipient_; } /// @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); for (uint256 i; i < fees.length; i++) { if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { __payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]); } } } /// @dev Helper to payout shares outstanding for a given fee. /// Assumes the fee is payout-able. function __payoutSharesOutstanding( address _comptrollerProxy, address _vaultProxy, address _fee ) private { uint256 sharesOutstanding = getFeeSharesOutstandingForFund(_comptrollerProxy, _fee); if (sharesOutstanding == 0) { return; } delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; address payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, _vaultProxy, payee, sharesOutstanding); emit SharesOutstandingPaidForFund(_comptrollerProxy, _fee, payee, sharesOutstanding); } /// @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 = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __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++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, 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++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // 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) public view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } // PUBLIC FUNCTIONS /// @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) public view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_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 "./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 payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function getRecipientForFund(address _comptrollerProxy) external view returns (address recipient_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function settlesOnHook(IFeeManager.FeeHook _hook) external view returns (bool settles_, bool usesGav_); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; function updatesOnHook(IFeeManager.FeeHook _hook) external view returns (bool updates_, bool usesGav_); } // 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, PreBuyShares, PostBuyShares, 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; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @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( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _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 "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.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 an external position to active external positions /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _externalPosition The external position to be added function __addExternalPosition(address _comptrollerProxy, address _externalPosition) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.AddExternalPosition, abi.encode(_externalPosition) ); } /// @notice Adds a tracked asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.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( IVault.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( IVault.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Executes a callOnExternalPosition /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _data The encoded data for the call function __callOnExternalPosition(address _comptrollerProxy, bytes memory _data) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.CallOnExternalPosition, _data ); } /// @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( IVault.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes an external position from the vaultProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _externalPosition The ExternalPosition to remove function __removeExternalPosition(address _comptrollerProxy, address _externalPosition) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.RemoveExternalPosition, abi.encode(_externalPosition) ); } /// @notice Removes a tracked asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.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( IVault.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( IVault.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; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @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 merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @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() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } }
SPDX-License-Identifier: GPL-3.0/ @title FeeManager Contract @author Enzyme Council <[email protected]> @notice Manages fees for funds @dev Any arbitrary fee is allowed by default, so all participants must be aware of their fund's configuration, especially whether they use official fees only. Fees can only be added upon fund setup, migration, or reconfiguration. EXTERNAL FUNCTIONS
contract FeeManager is IFeeManager, ExtensionBase, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using SafeMath for uint256; event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); 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, address indexed payee, uint256 sharesDue ); mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public ExtensionBase(_fundDeployer) {} function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } 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; } 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/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; function activateForFund(bool) external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory enabledFees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(comptrollerProxy, vaultProxy); } } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } 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; } 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/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; function activateForFund(bool) external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory enabledFees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(comptrollerProxy, vaultProxy); } } function deactivateForFund() external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory fees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < fees.length; i++) { __payoutSharesOutstanding(comptrollerProxy, vaultProxy, fees[i]); } } function deactivateForFund() external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory fees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < fees.length; i++) { __payoutSharesOutstanding(comptrollerProxy, vaultProxy, fees[i]); } } function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); __payoutSharesOutstandingForFees(msg.sender, _callArgs); revert("receiveCallFromComptroller: Invalid _actionId"); } } function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); __payoutSharesOutstandingForFees(msg.sender, _callArgs); revert("receiveCallFromComptroller: Invalid _actionId"); } } } else if (_actionId == 1) { } else { function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); for (uint256 i; i < fees.length; i++) { IFee(fees[i]).addFundSettings(_comptrollerProxy, settingsData[i]); comptrollerProxyToFees[_comptrollerProxy].push(fees[i]); emit FeeEnabledForFund(_comptrollerProxy, fees[i], settingsData[i]); } } function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); for (uint256 i; i < fees.length; i++) { IFee(fees[i]).addFundSettings(_comptrollerProxy, settingsData[i]); comptrollerProxyToFees[_comptrollerProxy].push(fees[i]); emit FeeEnabledForFund(_comptrollerProxy, fees[i], settingsData[i]); } } function __getGavAsNecessary(address _comptrollerProxy, uint256 _gavOrZero) private returns (uint256 gav_) { if (_gavOrZero == 0) { return IComptroller(_comptrollerProxy).calcGav(); return _gavOrZero; } } function __getGavAsNecessary(address _comptrollerProxy, uint256 _gavOrZero) private returns (uint256 gav_) { if (_gavOrZero == 0) { return IComptroller(_comptrollerProxy).calcGav(); return _gavOrZero; } } } else { function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = getEnabledFeesForFund(_comptrollerProxy); if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = getEnabledFeesForFund(_comptrollerProxy); if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } require(vaultProxy != address(0), "__invokeHook: Fund is not active"); uint256 gav = __settleFees( function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = getEnabledFeesForFund(_comptrollerProxy); if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } function __parseFeeRecipientForFund( address _comptrollerProxy, address _vaultProxy, address _fee ) private view returns (address recipient_) { recipient_ = IFee(_fee).getRecipientForFund(_comptrollerProxy); if (recipient_ == address(0)) { recipient_ = IVault(_vaultProxy).getOwner(); } return recipient_; } function __parseFeeRecipientForFund( address _comptrollerProxy, address _vaultProxy, address _fee ) private view returns (address recipient_) { recipient_ = IFee(_fee).getRecipientForFund(_comptrollerProxy); if (recipient_ == address(0)) { recipient_ = IVault(_vaultProxy).getOwner(); } return recipient_; } function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); for (uint256 i; i < fees.length; i++) { if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { __payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]); } } } function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); for (uint256 i; i < fees.length; i++) { if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { __payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]); } } } function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); for (uint256 i; i < fees.length; i++) { if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { __payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]); } } } function __payoutSharesOutstanding( address _comptrollerProxy, address _vaultProxy, address _fee ) private { uint256 sharesOutstanding = getFeeSharesOutstandingForFund(_comptrollerProxy, _fee); if (sharesOutstanding == 0) { return; } delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; address payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, _vaultProxy, payee, sharesOutstanding); emit SharesOutstandingPaidForFund(_comptrollerProxy, _fee, payee, sharesOutstanding); } function __payoutSharesOutstanding( address _comptrollerProxy, address _vaultProxy, address _fee ) private { uint256 sharesOutstanding = getFeeSharesOutstandingForFund(_comptrollerProxy, _fee); if (sharesOutstanding == 0) { return; } delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; address payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, _vaultProxy, payee, sharesOutstanding); emit SharesOutstandingPaidForFund(_comptrollerProxy, _fee, payee, sharesOutstanding); } 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 = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, payer, payee, sharesDue); payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __mintShares(_comptrollerProxy, payee, sharesDue); __burnShares(_comptrollerProxy, payer, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } 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 = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, payer, payee, sharesDue); payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __mintShares(_comptrollerProxy, payee, sharesDue); __burnShares(_comptrollerProxy, payer, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } 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 = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, payer, payee, sharesDue); payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __mintShares(_comptrollerProxy, payee, sharesDue); __burnShares(_comptrollerProxy, payer, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } } else if (settlementType == SettlementType.Mint) { } else if (settlementType == SettlementType.Burn) { } else if (settlementType == SettlementType.MintSharesOutstanding) { } else if (settlementType == SettlementType.BurnSharesOutstanding) { } else { 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++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, gav_); } __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } 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++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, gav_); } __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } 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++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, gav_); } __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } 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++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, gav_); } __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } 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++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } 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++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } 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++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } 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++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } function getEnabledFeesForFund(address _comptrollerProxy) public view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) public view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } }
223,728
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 4948, 48, 17, 23, 18, 20, 19, 225, 30174, 1318, 13456, 225, 1374, 94, 2942, 73, 385, 465, 71, 330, 411, 63, 3652, 131, 259, 1117, 65, 34, 225, 490, 940, 281, 1656, 281, 364, 284, 19156, 225, 5502, 11078, 14036, 353, 2935, 635, 805, 16, 1427, 777, 22346, 1297, 506, 18999, 434, 3675, 284, 1074, 1807, 1664, 16, 29440, 2856, 2898, 999, 3397, 22354, 1656, 281, 1338, 18, 5782, 281, 848, 1338, 506, 3096, 12318, 284, 1074, 3875, 16, 6333, 16, 578, 283, 7025, 18, 5675, 11702, 13690, 55, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 30174, 1318, 353, 11083, 1340, 1318, 16, 10021, 2171, 16, 8509, 329, 12003, 1803, 14439, 288, 203, 565, 1450, 5267, 1076, 5664, 364, 1758, 8526, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 30174, 1526, 1290, 42, 1074, 12, 203, 3639, 1758, 8808, 532, 337, 1539, 3886, 16, 203, 3639, 1758, 8808, 14036, 16, 203, 3639, 1731, 1947, 751, 203, 565, 11272, 203, 203, 565, 871, 30174, 694, 88, 1259, 1290, 42, 1074, 12, 203, 3639, 1758, 8808, 532, 337, 1539, 3886, 16, 203, 3639, 1758, 8808, 14036, 16, 203, 3639, 1000, 88, 806, 559, 8808, 26319, 806, 559, 16, 203, 3639, 1758, 293, 1773, 16, 203, 3639, 1758, 8843, 1340, 16, 203, 3639, 2254, 5034, 24123, 30023, 203, 565, 11272, 203, 203, 565, 871, 2638, 4807, 1182, 15167, 16507, 350, 1290, 42, 1074, 12, 203, 3639, 1758, 8808, 532, 337, 1539, 3886, 16, 203, 3639, 1758, 8808, 14036, 16, 203, 3639, 1758, 8808, 8843, 1340, 16, 203, 3639, 2254, 5034, 24123, 30023, 203, 565, 11272, 203, 203, 565, 2874, 12, 2867, 516, 1758, 63, 5717, 3238, 532, 337, 1539, 3886, 774, 2954, 281, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 203, 3639, 3238, 532, 337, 1539, 3886, 774, 14667, 774, 24051, 1182, 15167, 31, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 74, 1074, 10015, 264, 13, 1071, 10021, 2171, 24899, 74, 1074, 10015, 264, 13, 2618, 203, 565, 445, 527, 4402, 329, 6672, 12, 2867, 13, 3903, 2 ]
pragma solidity 0.5.11; import "../../utils/Bits.sol"; import "../../utils/PosLib.sol"; import "./OutputId.sol"; library ExitId { using PosLib for PosLib.Position; using Bits for uint168; using Bits for uint256; uint8 constant private FIRST_BIT_LOCATION = 167; /** * @notice Checks whether exitId is a standard exit ID */ function isStandardExit(uint168 exitId) internal pure returns (bool) { return exitId.getBit(FIRST_BIT_LOCATION) == 0; } /** * @notice Given transaction bytes and UTXO position, returns its exit ID * @dev Computation of a deposit ID is different to any other tx because txBytes of a deposit tx can be a non-unique value * @param isDeposit Defines whether the tx for the exitId is a deposit tx * @param txBytes Transaction bytes * @param utxoPos UTXO position of the exiting output * @return standardExitId Unique ID of the standard exit * Anatomy of returned value, most significant bits first: * 1-bit - in-flight flag (0 for standard exit) * 167-bits - outputId */ function getStandardExitId( bool isDeposit, bytes memory txBytes, PosLib.Position memory utxoPos ) internal pure returns (uint168) { bytes32 outputId; if (isDeposit) { outputId = OutputId.computeDepositOutputId(txBytes, utxoPos.outputIndex, utxoPos.encode()); } else { outputId = OutputId.computeNormalOutputId(txBytes, utxoPos.outputIndex); } return uint168((uint256(outputId) >> (256 - FIRST_BIT_LOCATION))); } /** * @notice Given transaction bytes, returns in-flight exit ID * @param txBytes Transaction bytes * @return Unique in-flight exit ID */ function getInFlightExitId(bytes memory txBytes) internal pure returns (uint168) { return uint168((uint256(keccak256(txBytes)) >> (256 - FIRST_BIT_LOCATION)).setBit(FIRST_BIT_LOCATION)); } }
* @notice Given transaction bytes, returns in-flight exit ID @param txBytes Transaction bytes @return Unique in-flight exit ID/
function getInFlightExitId(bytes memory txBytes) internal pure returns (uint168) { return uint168((uint256(keccak256(txBytes)) >> (256 - FIRST_BIT_LOCATION)).setBit(FIRST_BIT_LOCATION)); }
12,687,072
[ 1, 6083, 2492, 1731, 16, 1135, 316, 17, 19131, 2427, 1599, 225, 2229, 2160, 5947, 1731, 327, 14584, 316, 17, 19131, 2427, 1599, 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, 565, 445, 7854, 24243, 6767, 548, 12, 3890, 3778, 2229, 2160, 13, 2713, 16618, 1135, 261, 11890, 23329, 13, 288, 203, 3639, 327, 2254, 23329, 12443, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 978, 2160, 3719, 1671, 261, 5034, 300, 21786, 67, 15650, 67, 15277, 13, 2934, 542, 5775, 12, 15354, 67, 15650, 67, 15277, 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 ]
./full_match/5/0x50D80C9fD54a8ceCBF199d7Ee8d9F6207D27d316/sources/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, non-reverting calls are assumed to be successful./
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"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } }
1,888,425
[ 1, 23326, 448, 326, 4440, 6835, 1807, 1699, 1359, 358, 2913, 1375, 87, 1302, 264, 68, 635, 1375, 1132, 8338, 971, 1375, 2316, 68, 1135, 1158, 460, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4183, 23326, 448, 7009, 1359, 12, 45, 654, 39, 3462, 1147, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 5034, 1592, 7009, 1359, 273, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 1769, 203, 5411, 2583, 12, 1673, 7009, 1359, 1545, 460, 16, 315, 9890, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 8863, 203, 5411, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 17571, 264, 16, 1592, 7009, 1359, 300, 460, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8a9072Aa85C3Cf578503a5714319fF2F5B08C521/sources/Team3D.sol
Trade start checkSet Fee for BuysSet Fee for Sells
function _transfer( address from, address to, uint256 amount ) private { require(to != address(0), "ERC20: transfer to the zero address"); require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( from != owner() && to != owner() ) { if (!start_trading) { require( from == owner(), "Error: This account cannot send tokens until trading is enabled" ); } require(amount <= _maxTxSizeAmount, "Error: Max Transaction Limit"); if(to != _pairUniv2Address) { require(balanceOf(to) + amount < _max_wallet_limit_size, "Error: Balance exceeds wallet size!"); } uint256 contractBalanceForTokens = balanceOf(address(this)); bool canSwap = contractBalanceForTokens >= _swap_amount_at; if (_swap_active && canSwap && !_ok_swapping && from != _pairUniv2Address && !_is_excluded_from_fee[from] && !_is_excluded_from_fee[to] ) { swapBack(contractBalanceForTokens); uint256 balanceOfEth = address(this).balance; if (balanceOfEth > 0) { sendAllEth(address(this).balance); } } } bool takingFee = true; (_is_excluded_from_fee[from] || _is_excluded_from_fee[to]) || (from != _pairUniv2Address && to != _pairUniv2Address) ) { takingFee = false; if(from == _pairUniv2Address && to != address(uniswapV2Router)) { _marketing_tax = _marketing_buy_fee_amount; _dev_tax = _dev_buy_fee_amount; } if (to == _pairUniv2Address && from != address(uniswapV2Router)) { _marketing_tax = _sell_market_fee_amount; _dev_tax = _sell_dev_fee_amount; } } _transferTokensWithTax(from, to, amount, takingFee); }
9,425,294
[ 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, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 7010, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 3639, 309, 261, 203, 5411, 628, 480, 3410, 1435, 7010, 5411, 597, 358, 480, 3410, 1435, 203, 3639, 262, 288, 203, 5411, 309, 16051, 1937, 67, 313, 14968, 13, 288, 203, 7734, 2583, 12, 203, 10792, 628, 422, 3410, 9334, 7010, 10792, 315, 668, 30, 1220, 2236, 2780, 1366, 2430, 3180, 1284, 7459, 353, 3696, 6, 203, 7734, 11272, 203, 5411, 289, 203, 5411, 2583, 12, 8949, 1648, 389, 1896, 4188, 1225, 6275, 16, 315, 668, 30, 4238, 5947, 7214, 8863, 203, 5411, 309, 12, 869, 480, 389, 6017, 984, 427, 22, 1887, 13, 288, 203, 7734, 2583, 12, 12296, 951, 12, 869, 13, 397, 3844, 411, 389, 1896, 67, 19177, 67, 3595, 67, 1467, 16, 203, 1171, 315, 668, 30, 30918, 14399, 9230, 963, 4442, 1769, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 6835, 13937, 1290, 5157, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 1426, 848, 12521, 273, 6835, 13937, 1290, 5157, 1545, 389, 22270, 67, 8949, 67, 270, 31, 203, 203, 5411, 309, 2 ]
./full_match/100/0x2594Abb99524d208C199a3F3F4B25243Ad49893e/sources/smartcontract-lottery-main/contracts/test/MockOracle.sol
* @title The Chainlink Mock Oracle contract @notice Chainlink smart contract developers can use this to test their contracts/
contract MockOracle is ChainlinkRequestInterface, LinkTokenReceiver { using SafeMathChainlink for uint256; uint256 constant public EXPIRY_TIME = 5 minutes; uint256 constant private MINIMUM_CONSUMER_GAS_LIMIT = 400000; pragma solidity ^0.6.0; struct Request { address callbackAddr; bytes4 callbackFunctionId; } LinkTokenInterface internal LinkToken; mapping(bytes32 => Request) private commitments; event OracleRequest( bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data ); event CancelOracleRequest( bytes32 indexed requestId ); public constructor(address _link) { } function oracleRequest( address _sender, uint256 _payment, bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionId, uint256 _nonce, uint256 _dataVersion, bytes calldata _data ) external override onlyLINK() checkCallbackAddress(_callbackAddress) { bytes32 requestId = keccak256(abi.encodePacked(_sender, _nonce)); require(commitments[requestId].callbackAddr == address(0), "Must use a unique ID"); uint256 expiration = now.add(EXPIRY_TIME); commitments[requestId] = Request( _callbackAddress, _callbackFunctionId ); emit OracleRequest( _specId, _sender, requestId, _payment, _callbackAddress, _callbackFunctionId, expiration, _dataVersion, _data); } function fulfillOracleRequest( bytes32 _requestId, bytes32 _data ) external isValidRequest(_requestId) returns (bool) { Request memory req = commitments[_requestId]; delete commitments[_requestId]; require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); return success; } function cancelOracleRequest( bytes32 _requestId, uint256 _payment, bytes4, uint256 _expiration ) external override { require(commitments[_requestId].callbackAddr != address(0), "Must use a unique ID"); require(_expiration <= now, "Request is not expired"); delete commitments[_requestId]; emit CancelOracleRequest(_requestId); assert(LinkToken.transfer(msg.sender, _payment)); } function getChainlinkToken() public view override returns (address) { return address(LinkToken); } modifier isValidRequest(bytes32 _requestId) { require(commitments[_requestId].callbackAddr != address(0), "Must have a valid requestId"); _; } modifier checkCallbackAddress(address _to) { require(_to != address(LinkToken), "Cannot callback to LINK"); _; } }
14,277,929
[ 1, 1986, 7824, 1232, 7867, 28544, 6835, 225, 7824, 1232, 13706, 6835, 21701, 848, 999, 333, 358, 1842, 3675, 20092, 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 ]
[ 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, 7867, 23601, 353, 7824, 1232, 13398, 16, 4048, 1345, 12952, 288, 203, 225, 1450, 14060, 10477, 3893, 1232, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 5381, 1071, 31076, 9590, 67, 4684, 273, 1381, 6824, 31, 203, 225, 2254, 5034, 5381, 3238, 6989, 18605, 67, 31668, 67, 43, 3033, 67, 8283, 273, 1059, 11706, 31, 203, 282, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 225, 1958, 1567, 288, 203, 1377, 1758, 1348, 3178, 31, 203, 1377, 1731, 24, 1348, 2083, 548, 31, 203, 225, 289, 203, 203, 225, 4048, 1345, 1358, 2713, 4048, 1345, 31, 203, 225, 2874, 12, 3890, 1578, 516, 1567, 13, 3238, 3294, 1346, 31, 203, 203, 225, 871, 28544, 691, 12, 203, 565, 1731, 1578, 8808, 857, 548, 16, 203, 565, 1758, 19961, 16, 203, 565, 1731, 1578, 14459, 16, 203, 565, 2254, 5034, 5184, 16, 203, 565, 1758, 1348, 3178, 16, 203, 565, 1731, 24, 1348, 2083, 548, 16, 203, 565, 2254, 5034, 3755, 12028, 16, 203, 565, 2254, 5034, 501, 1444, 16, 203, 565, 1731, 501, 203, 225, 11272, 203, 203, 225, 871, 10347, 23601, 691, 12, 203, 565, 1731, 1578, 8808, 14459, 203, 225, 11272, 203, 203, 565, 1071, 203, 225, 3885, 12, 2867, 389, 1232, 13, 203, 225, 288, 203, 225, 289, 203, 203, 225, 445, 20865, 691, 12, 203, 565, 1758, 389, 15330, 16, 203, 565, 2254, 5034, 389, 9261, 16, 203, 565, 1731, 1578, 389, 2793, 548, 16, 203, 565, 1758, 389, 3394, 1887, 16, 203, 2 ]
pragma solidity ^0.4.19; import "./Agricoin.sol"; import "./Owned.sol"; contract Ico is Owned { enum State { Runned, // Ico is running. Paused, // Ico was paused. Finished, // Ico has finished successfully. Expired, // Ico has finished unsuccessfully. Failed } // Refund event. event Refund(address indexed investor, uint amount); // Investment event. event Invested(address indexed investor, uint amount); // End of ICO event. event End(bool result); // Ico constructor. function Ico( address tokenAddress, // Agricoin contract address. uint tokenPreIcoPrice, // Price of Agricoin in weis on Pre-ICO. uint tokenIcoPrice, // Price of Agricoin in weis on ICO. uint preIcoStart, // Date of Pre-ICO start. uint preIcoEnd, // Date of Pre-ICO end. uint icoStart, // Date of ICO start. uint icoEnd, // Date of ICO end. uint preIcoEmissionTarget, // Max number of Agricoins, which will be minted on Pre-ICO. uint icoEmissionTarget, // Max number of Agricoins, which will be minted on ICO. uint icoSoftCap) public { owner = msg.sender; token = tokenAddress; state = State.Runned; // Save prices. preIcoPrice = tokenPreIcoPrice; icoPrice = tokenIcoPrice; // Save dates. startPreIcoDate = preIcoStart; endPreIcoDate = preIcoEnd; startIcoDate = icoStart; endIcoDate = icoEnd; preIcoTarget = preIcoEmissionTarget; icoTarget = icoEmissionTarget; softCap = icoSoftCap; } // Returns true if ICO is active now. function isActive() public view returns (bool) { return state == State.Runned; } // Returns true if date in Pre-ICO period. function isRunningPreIco(uint date) public view returns (bool) { return startPreIcoDate <= date && date <= endPreIcoDate; } // Returns true if date in ICO period. function isRunningIco(uint date) public view returns (bool) { return startIcoDate <= date && date <= endIcoDate; } // Fallback payable function. function () external payable { // Initialize variables here. uint value; uint rest; uint amount; if (state == State.Failed) { amount = invested[msg.sender] + investedOnPreIco[msg.sender];// Save amount of invested weis for user. invested[msg.sender] = 0;// Set amount of invested weis to zero. investedOnPreIco[msg.sender] = 0; Refund(msg.sender, amount);// Call refund event. msg.sender.transfer(amount + msg.value);// Returns funds to user. return; } if (state == State.Expired)// Unsuccessful end of ICO. { amount = invested[msg.sender];// Save amount of invested weis for user. invested[msg.sender] = 0;// Set amount of invested weis to zero. Refund(msg.sender, amount);// Call refund event. msg.sender.transfer(amount + msg.value);// Returns funds to user. return; } require(state == State.Runned);// Only for active contract. if (now >= endIcoDate)// After ICO period. { if (Agricoin(token).totalSupply() + Agricoin(token).totalSupplyOnIco() >= softCap)// Minted Agricoin amount above fixed SoftCap. { state = State.Finished;// Set state to Finished. // Get Agricoin info for bounty. uint decimals = Agricoin(token).decimals(); uint supply = Agricoin(token).totalSupply() + Agricoin(token).totalSupplyOnIco(); // Transfer bounty funds to Bounty contract. if (supply >= 1500000 * decimals) { Agricoin(token).mint(bounty, 300000 * decimals, true); } else if (supply >= 1150000 * decimals) { Agricoin(token).mint(bounty, 200000 * decimals, true); } else if (supply >= 800000 * decimals) { Agricoin(token).mint(bounty, 100000 * decimals, true); } Agricoin(token).activate(true);// Activate Agricoin contract. End(true);// Call successful end event. msg.sender.transfer(msg.value);// Returns user's funds to user. return; } else// Unsuccessful end. { state = State.Expired;// Set state to Expired. Agricoin(token).activate(false);// Activate Agricoin contract. msg.sender.transfer(msg.value);// Returns user's funds to user. End(false);// Call unsuccessful end event. return; } } else if (isRunningPreIco(now))// During Pre-ICO. { require(investedSumOnPreIco / preIcoPrice < preIcoTarget);// Check for target. if ((investedSumOnPreIco + msg.value) / preIcoPrice >= preIcoTarget)// Check for target with new weis. { value = preIcoTarget * preIcoPrice - investedSumOnPreIco;// Value of invested weis without change. require(value != 0);// Check value isn't zero. investedSumOnPreIco = preIcoTarget * preIcoPrice;// Max posible number of invested weis in to Pre-ICO. investedOnPreIco[msg.sender] += value;// Increase invested funds by investor. Invested(msg.sender, value);// Call investment event. Agricoin(token).mint(msg.sender, value / preIcoPrice, false);// Mint some Agricoins for investor. msg.sender.transfer(msg.value - value);// Returns change to investor. return; } else { rest = msg.value % preIcoPrice;// Calculate rest/change. require(msg.value - rest >= preIcoPrice); investedSumOnPreIco += msg.value - rest; investedOnPreIco[msg.sender] += msg.value - rest; Invested(msg.sender, msg.value - rest);// Call investment event. Agricoin(token).mint(msg.sender, msg.value / preIcoPrice, false);// Mint some Agricoins for investor. msg.sender.transfer(rest);// Returns change to investor. return; } } else if (isRunningIco(now))// During ICO. { require(investedSumOnIco / icoPrice < icoTarget);// Check for target. if ((investedSumOnIco + msg.value) / icoPrice >= icoTarget)// Check for target with new weis. { value = icoTarget * icoPrice - investedSumOnIco;// Value of invested weis without change. require(value != 0);// Check value isn't zero. investedSumOnIco = icoTarget * icoPrice;// Max posible number of invested weis in to ICO. invested[msg.sender] += value;// Increase invested funds by investor. Invested(msg.sender, value);// Call investment event. Agricoin(token).mint(msg.sender, value / icoPrice, true);// Mint some Agricoins for investor. msg.sender.transfer(msg.value - value);// Returns change to investor. return; } else { rest = msg.value % icoPrice;// Calculate rest/change. require(msg.value - rest >= icoPrice); investedSumOnIco += msg.value - rest; invested[msg.sender] += msg.value - rest; Invested(msg.sender, msg.value - rest);// Call investment event. Agricoin(token).mint(msg.sender, msg.value / icoPrice, true);// Mint some Agricoins for investor. msg.sender.transfer(rest);// Returns change to investor. return; } } else { revert(); } } // Pause contract. function pauseIco() onlyOwner external { require(state == State.Runned);// Only from Runned state. state = State.Paused;// Set state to Paused. } // Continue paused contract. function continueIco() onlyOwner external { require(state == State.Paused);// Only from Paused state. state = State.Runned;// Set state to Runned. } // End contract unsuccessfully. function endIco() onlyOwner external { require(state == State.Paused);// Only from Paused state. state = State.Failed;// Set state to Expired. } // Get invested ethereum. function getEthereum() onlyOwner external returns (uint) { require(state == State.Finished);// Only for successfull ICO. uint amount = this.balance;// Save balance. msg.sender.transfer(amount);// Transfer all funds to owner address. return amount;// Returns amount of transfered weis. } // Get invested ethereum from Pre ICO. function getEthereumFromPreIco() onlyOwner external returns (uint) { require(now >= endIcoDate); uint value = investedSumOnPreIco; investedSumOnPreIco = 0; msg.sender.transfer(value); return value; } // Invested balances. mapping (address => uint) invested; mapping (address => uint) investedOnPreIco; // State of contract. State public state; // Agricoin price in weis on Pre-ICO. uint public preIcoPrice; // Agricoin price in weis on ICO. uint public icoPrice; // Date of Pre-ICO start. uint public startPreIcoDate; // Date of Pre-ICO end. uint public endPreIcoDate; // Date of ICO start. uint public startIcoDate; // Date of ICO end. uint public endIcoDate; // Agricoin contract address. address public token; // Bounty contract address. address public bounty; // Invested sum in weis on Pre-ICO. uint public investedSumOnPreIco = 0; // Invested sum in weis on ICO. uint public investedSumOnIco = 0; // Target in tokens minted on Pre-ICo. uint public preIcoTarget; // Target in tokens minted on ICO. uint public icoTarget; // SoftCap fot this ICO. uint public softCap; }
Set state to Runned.
state = State.Runned;
5,518,111
[ 1, 694, 919, 358, 1939, 11748, 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 ]
[ 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, 919, 273, 3287, 18, 1997, 11748, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/PLBTStaking/IPLBTStaking.sol"; import "./interfaces/DAO/IDAO.sol"; import "./sushiswap/IUniswapV2Router02.sol"; import "./gysr/ERC20FriendlyRewardModule.sol"; import "./gysr/PoolFactory.sol"; import "./gysr/interfaces/IPool.sol"; ///@title DAO contract contract DAO is IDAO, AccessControl { using SafeERC20 for IERC20; /// status of vote enum Decision { none, votedFor, votedAgainst } /// type of proposal types enum ChangesType { none, strategy, allocation, quorum, majority, treasury, cancel } /// state of proposal enum Status { none, proposal, finished, voting } /// struct represents a vote struct Vote { // amount of tokens in vote uint256 amount; // voting decision Decision decision; } /// struct for storing proposal struct Voting { // voting id uint256 id; // in support of votes uint256 votesFor; // against votes uint256 votesAgainst; // when started uint256 startTime; // voting may execute only after voting ended uint256 endTime; // this time increases if this voting is being cancelled uint256 finishTime; // time when changes come in power uint256 implementationTime; // creator address address creator; // address of proposal creator ChangesType changesType; // proposal status Status status; // indicator showing if proposal was cancelled bool wasCancelled; // bytecode to run on the finishvote bytes data; } /// represents allocation percentage struct Allocation { uint8 plbtStakers; uint8 osomStakers; uint8 lpStakers; uint8 buyback; } /// represents amount of tokens in percentage put on investing strategies struct Strategy { uint8 autopilot; uint8 uniswap; uint8 aave; uint8 anchor; } ///@dev emmited when new proposal created ///@param creator address of proposal creator ///@param key hash passed to event in order to match with backend, for storing proposal descriptions ///@param id id of proposal ///@param startTime time when voting on proposal starts ///@param endTime time when voting on proposal ends event ProposalAdded( address indexed creator, bytes32 key, uint256 indexed id, uint256 startTime, uint256 endTime ); ///@dev emmited when proposal transitioned to main voting status ///@param id id of proposal ///@param startTime time when main voting starts ///@param endTime time when main voting ends event VotingBegan(uint256 indexed id, uint256 startTime, uint256 endTime); ///@dev emmited when voting is finished ///@param id id of finished proposal ///@param executed shows if finish was successfully executed ///@param votesFor with how many tokens voted for proposal ///@param votesAgainst with how many tokens voted against proposal event Finished( uint256 indexed id, bool indexed executed, uint256 votesFor, uint256 votesAgainst ); ///@dev emmited when someone voted on proposal ///@param voter address of voter ///@param id id of proposal ///@param decision shows if voted for or against ///@param amount amount of tokens voted with event CastedOnProposal( address indexed voter, uint256 indexed id, bool decision, uint256 amount ); ///@dev emmited when someone voted in main voting ///@param voter address of voter ///@param id id of proposal ///@param decision shows if voted for or against ///@param amount amount of tokens voted with event CastedOnVoting( address indexed voter, uint256 indexed id, bool decision, uint256 amount ); ///@dev modifier used for restricted function execution modifier onlyDAO() { require( msg.sender == address(this), "DAO: only dao can call this function." ); _; } /// role of treasury holder bytes32 public TREASURY_ROLE = keccak256("TREASURY_ROLE"); /// threshold for proposal to pass uint256 public proposalMajority; ///threshold for voting to pass uint256 public votingMajority; /// threshold for proposal to become valid uint256 public proposalQuorum; /// threshold for voting to become valid uint256 public votingQuorum; /// debating period duration uint256 public votingPeriod; /// voting count uint256 public votingsCount; /// regular timelock uint256 public regularTimelock; /// cancel timelock uint256 public cancelTimelock; /// Allocation Allocation public allocation; /// Strategy Strategy public strategy; /// Treasury owner address treasury; /// for percent calculations uint256 private precision = 1e6; /// staking contracts IPLBTStaking private staking; /// tokens IERC20 private plbt; IERC20 private weth; IERC20 private wbtc; /// Router IUniswapV2Router02 router; ///pool address address public pool; ///GYSR Pool address public gysr; ///OSOM address address OSOM; ///array of function selectors bytes4[6] selectors = [ this.changeStrategy.selector, this.changeAllocation.selector, this.changeQuorum.selector, this.changeMajority.selector, this.changeTreasury.selector, this.cancelVoting.selector ]; /// active proposals uint256[10] public proposals; /// initialized bool private initialized; mapping(uint256 => Voting) public votings; /// storing votes from a certain address for voting mapping(uint256 => mapping(address => Vote)) public votingDecisions; /// current voting uint256 public activeVoting; /// current cancel uint256 public activeCancellation; ///@param _proposalMajority initial percent of proposal majority of votes to become valid ///@param _votingMajority initial percent of main voting majority of votes to become valid ///@param _proposalQuorum initial percent of proposal quorum ///@param _votingQuorum initial percent of main voting quorum ///@param _votingPeriod initial voting period time ///@param _regularTimelock initial timelock period ///@param _cancelTimelock initial cancel timelock period ///@param _allocation initial allocation config ///@param _strategy initial strategy config constructor( uint256 _proposalMajority, uint256 _votingMajority, uint256 _proposalQuorum, uint256 _votingQuorum, uint256 _votingPeriod, uint256 _regularTimelock, uint256 _cancelTimelock, Allocation memory _allocation, Strategy memory _strategy ) { proposalMajority = _proposalMajority; votingMajority = _votingMajority; proposalQuorum = _proposalQuorum; votingQuorum = _votingQuorum; votingPeriod = _votingPeriod; regularTimelock = _regularTimelock; cancelTimelock = _cancelTimelock; allocation = _allocation; strategy = _strategy; _setupRole(DEFAULT_ADMIN_ROLE, address(this)); _setRoleAdmin(TREASURY_ROLE, DEFAULT_ADMIN_ROLE); } ///@dev initializing DAO with settings ///@param _router SushiSwap router address ///@param _treasury address of the treasury holder ///@param _stakingAddr address of staking ///@param _plbt Polybius token address ///@param _weth address of wEth ///@param _wbtc address of wBTC ///@param _poolFactory address of GYSR pool factory ///@param _stakingFactory address of GYSR staking module Factory ///@param _rewardFactory address of GYSR reward module factory ///@param _slpAddress address of PLBT-wETH LP token address ///@param _OSOM address of OSOM function initialize( address _router, address _treasury, address _stakingAddr, address _plbt, address _weth, address _wbtc, address _poolFactory, address _stakingFactory, address _rewardFactory, address _slpAddress, address _OSOM ) external { require(!initialized, "DAO: Already initialized."); treasury = _treasury; _setupRole(TREASURY_ROLE, treasury); staking = IPLBTStaking(_stakingAddr); plbt = IERC20(_plbt); weth = IERC20(_weth); wbtc = IERC20(_wbtc); PoolFactory factory = PoolFactory(_poolFactory); bytes memory stakingdata = (abi.encode(_slpAddress)); bytes memory rewarddata = (abi.encode(_plbt, 10**18, 2592000)); pool = factory.create( _stakingFactory, _rewardFactory, stakingdata, rewarddata ); gysr = IPool(pool).rewardModule(); OSOM = _OSOM; router = IUniswapV2Router02(_router); _setupRole(TREASURY_ROLE, treasury); initialized = true; } ///@dev distributing fund to parties and staking contracts, and buying back PLBT from Sushiswap pool ///@param toStakersWETH amount of wETH to distribute to PLBTStakers ///@param toStakersWBTC amount of wBTC to distribute to PLBTStakers ///@param toLPStakers amount of PLBT to distribute to LPStakers on GYSR ///@param toOSOMWETH amount of wETH to distribute to PLBTStakers on OSOM ///@param toOSOMWBTC amount of wBTC to distribute to PLBTStakers on OSOM ///@param toBuyback amount of wETH to swap for PLBT function distribute( uint256 toStakersWETH, uint256 toStakersWBTC, uint256 toLPStakers, uint256 toOSOMWETH, uint256 toOSOMWBTC, uint256 toBuyback ) external onlyRole(TREASURY_ROLE) { if (toStakersWETH != 0 && toStakersWBTC != 0) { weth.safeTransferFrom(treasury, address(staking), toStakersWETH); wbtc.safeTransferFrom(treasury, address(staking), toStakersWBTC); staking.setReward(toStakersWETH, toStakersWBTC); } if (toLPStakers != 0) { plbt.safeTransferFrom(treasury, address(this), toLPStakers); plbt.approve(gysr, toLPStakers); ERC20FriendlyRewardModule(gysr).fund(toLPStakers, 2592000); } if (toOSOMWETH != 0 && toOSOMWBTC != 0) { weth.safeTransferFrom(treasury, OSOM, toOSOMWETH); wbtc.safeTransferFrom(treasury, OSOM, toOSOMWBTC); } if (toBuyback != 0) { uint256 total = plbt.balanceOf(address(this)); weth.safeTransferFrom(treasury, address(this), toBuyback); address[] memory path = new address[](2); path[0] = address(weth); path[1] = address(plbt); uint256[] memory amounts = router.getAmountsOut(toBuyback, path); weth.approve(address(router), amounts[0]); router.swapTokensForExactTokens( amounts[1], amounts[0], path, address(this), block.timestamp + 600 ); uint256 current = plbt.balanceOf(address(this)); uint256 burn = current - total; plbt.safeTransfer(address(0), burn); } } function changeOSOM(address _address) external onlyRole(TREASURY_ROLE) { require(_address != address(0), "DAO: can't set zero-address"); OSOM = _address; } ///@dev function which matches function selector with bytecode ///@param _changesType shows which function selector is expected ///@param _data bytecode to match modifier matchChangesTypes(ChangesType _changesType, bytes memory _data) { require( _changesType != ChangesType.none, "DAO: addProposal bad arguments." ); bytes4 outBytes4; assembly { outBytes4 := mload(add(_data, 0x20)) } require( outBytes4 == selectors[uint256(_changesType) - 1], "DAO: bytecode is wrong" ); _; } ///@dev function which will be called on Finish; changes proposal or main voting quorums ///@param or shows what quorum to change ///@param _quorum new quorum percent value function changeQuorum(bool or, uint256 _quorum) public onlyDAO { or ? votingQuorum = _quorum : proposalQuorum = _quorum; } ///@dev function which will be called on Finish; changes proposal or main voting Majority ///@param or shows what Majority to change ///@param _majority new Majority percent value function changeMajority(bool or, uint256 _majority) public onlyDAO { or ? votingMajority = _majority : proposalMajority = _majority; } ///@dev function which will be called on Finish of cancellation voting ///@param id id of main voting function cancelVoting(uint256 id) public onlyDAO { votings[id].status = Status.finished; } ///@dev function which will be called on Finish; changes allocation parameters ///@param _allocation new allocation config function changeAllocation(Allocation memory _allocation) public onlyDAO { allocation = _allocation; } ///@dev function which will be called on Finish; changes strategy parameters ///@param _strategy new strategy config function changeStrategy(Strategy memory _strategy) public onlyDAO { strategy = _strategy; } ///@dev function which will be called on Finish; changes treasury holder address ///@param _treasury new treasury holder address function changeTreasury(address _treasury) public onlyDAO { revokeRole(TREASURY_ROLE, treasury); treasury = _treasury; grantRole(TREASURY_ROLE, treasury); staking.changeTreasury(_treasury); } ///@dev check if proposal passed quorum and majority thresholds ///@param proposal proposal sent to validate function validate(Voting memory proposal) private view returns (bool) { uint256 total = proposal.votesFor + proposal.votesAgainst; if (total == 0) { return false; } bool quorum; uint256 supply = plbt.totalSupply() - plbt.balanceOf(address(0)); bool majority; if (proposal.status == Status.voting) { quorum = ((total * precision) / supply) > votingQuorum; majority = (proposal.votesFor * precision) / total > votingMajority; } else { quorum = ((total * precision) / supply) > proposalQuorum; majority = (proposal.votesFor * precision) / total > proposalMajority; } return majority && quorum; } ///@dev picks next proposal out of proposal pool function pickProposal() private view returns (uint256 id, bool check) { if (votings[activeVoting].status == Status.voting) { return (0, false); } uint256 temp = 0; Voting memory proposal; for (uint256 i = 0; i < proposals.length; i++) { proposal = votings[proposals[i]]; if (proposal.status == Status.proposal && validate(proposal)) { (temp == 0 || proposal.startTime < votings[temp].startTime) ? temp = proposal.id : 0; } } if (temp != 0 && validate(votings[temp])) { return (temp, true); } return (0, false); } ///@dev send proposal to main voting round ///@param id id of proposal function sendProposalToVoting(uint256 id) private { Voting storage proposal = votings[id]; proposal.status = Status.voting; proposal.startTime = block.timestamp; proposal.endTime = block.timestamp + votingPeriod; proposal.finishTime = proposal.endTime + regularTimelock; activeVoting = id; emit VotingBegan(proposal.id, proposal.startTime, proposal.endTime); } ///@dev adds proposal to proposal pool ///@param _changesType type of proposal ///@param _data executable bytecode to execute on Finish ///@param id key for matching frontend request with this contract logs function addProposal( ChangesType _changesType, bytes memory _data, bytes32 id ) public matchChangesTypes(_changesType, _data) { bool cancel = _changesType == ChangesType.cancel; require( !(cancel && votings[activeCancellation].status == Status.voting), "Cancel Voting already exists" ); if (cancel) { Voting storage voting = votings[activeVoting]; require( voting.wasCancelled == false && voting.status == Status.voting, "DAO: Can't cancel twice." ); require( voting.endTime < block.timestamp && voting.finishTime > block.timestamp, "DAO: can only cancel during timelock" ); voting.finishTime = block.timestamp + cancelTimelock; voting.wasCancelled = true; } votingsCount++; Voting memory proposal = Voting({ id: votingsCount, votesFor: 0, votesAgainst: 0, startTime: block.timestamp, endTime: block.timestamp + votingPeriod, finishTime: 0, implementationTime: 0, creator: msg.sender, changesType: _changesType, status: Status.proposal, wasCancelled: false, data: _data }); votings[votingsCount] = proposal; if (cancel) { activeCancellation = votingsCount; votings[activeCancellation].status = Status.voting; votings[activeCancellation].finishTime = votings[activeCancellation] .endTime; emit ProposalAdded( msg.sender, id, votingsCount, proposal.startTime, proposal.endTime ); return; } bool proposalAdded = false; bool check; for (uint256 i = 0; i < proposals.length; i++) { if ( votings[proposals[i]].status != Status.proposal || proposals[i] == 0 ) { check = true; } else { if ( votings[proposals[i]].endTime <= block.timestamp && votings[proposals[i]].status == Status.proposal ) { check = !(validate(votings[proposals[i]])); } } if (check) { proposals[i] = proposal.id; proposalAdded = true; break; } } require(proposalAdded, "DAO: proposals list is full"); emit ProposalAdded( msg.sender, id, votingsCount, proposal.startTime, proposal.endTime ); } ///@dev participate in main voting round ///@param id id of proposal ///@param amount amount of tokens to vote with ///@param decision shows if voted for or against function participateInVoting( uint256 id, uint256 amount, bool decision ) external { // check if proposal is active bool check = votings[id].status == Status.voting && votings[id].endTime >= block.timestamp; require(check, "DAO: voting ended"); // check if voted Vote storage vote = votingDecisions[id][msg.sender]; require( vote.decision == Decision.none && vote.amount == 0, "DAO: you have already voted" ); // check if msg.sender has available tokens uint256 possible = getAvailableTokens(msg.sender); require(amount > 0 && amount <= possible, "DAO: incorrect amount"); Voting storage voting = votings[id]; vote.amount += amount; if (decision) { voting.votesFor += amount; vote.decision = Decision.votedFor; } else { voting.votesAgainst += amount; vote.decision = Decision.votedAgainst; } emit CastedOnVoting(msg.sender, id, decision, amount); } ///@dev participate in proposal ///@param id id of proposal ///@param amount amount of tokens to vote with ///@param decision shows if voted for or against function participateInProposal( uint256 id, uint256 amount, bool decision ) external { // check if proposal is active bool check = votings[id].status == Status.proposal && votings[id].endTime >= block.timestamp; require(check, "DAO: proposal ended"); // check if voted Voting storage proposal = votings[id]; Vote storage vote = votingDecisions[proposal.id][msg.sender]; require( vote.decision == Decision.none && vote.amount == 0, "DAO: you have already voted" ); // check if msg.sender has available tokens uint256 possible = getAvailableTokens(msg.sender); require(amount > 0 && amount <= possible, "DAO: incorrect amount"); vote.amount += amount; if (decision) { proposal.votesFor += amount; vote.decision = Decision.votedFor; } else { proposal.votesAgainst += amount; vote.decision = Decision.votedAgainst; } votings[proposal.id] = proposal; (uint256 picked, bool found) = pickProposal(); if (found) { sendProposalToVoting(picked); } emit CastedOnProposal(msg.sender, id, decision, amount); } ///@dev to finish main voting round and run changes on success ///@param id id of proposal to finish function finishVoting(uint256 id) public { Voting storage voting = votings[id]; require( (voting.status == Status.voting), "DAO: the result of the vote has already been completed," ); require( block.timestamp > (voting.finishTime), "DAO: Voting can't be finished yet." ); bool result = validate(voting); if (result && voting.changesType != ChangesType.cancel) { (bool success, ) = address(this).call{value: 0}(voting.data); voting.implementationTime = block.timestamp; } if (voting.changesType == ChangesType.cancel) { if (result) { address(this).call{value: 0}(voting.data); } else { bytes memory data = voting.data; uint256 id_; assembly { let sig := mload(add(data, add(4, 0))) id_ := mload(add(data, 36)) } votings[id_].finishTime = votings[id_].endTime; finishVoting(id_); } } voting.status = Status.finished; (uint256 picked, bool found) = pickProposal(); if (found) { sendProposalToVoting(picked); } emit Finished(id, result, voting.votesFor, voting.votesAgainst); } ///@dev used for situations, when previously passed proposal wasn't finished and proposal pool is full ///@param finishId id of proposal to finish ///@param _changesType type of proposal ///@param _data executable bytecode to execute on Finish ///@param id key for matching frontend request with this contract logs function finishAndAddProposal( uint256 finishId, ChangesType _changesType, bytes calldata _data, bytes32 id ) external { finishVoting(finishId); addProposal(_changesType, _data, id); } ///@dev get all locked tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals ///@param staker address of staker function getLockedTokens(address staker) public view override returns (uint256 locked) { for (uint256 i = 0; i < proposals.length; i++) { if ( (votings[proposals[i]].endTime > block.timestamp || validate(votings[proposals[i]])) && votings[proposals[i]].status == Status.proposal ) locked += votingDecisions[proposals[i]][staker].amount; } if ( votings[activeVoting].status == Status.voting && votings[activeVoting].finishTime > block.timestamp ) { locked += votingDecisions[activeVoting][staker].amount; } if ( votings[activeCancellation].status == Status.voting && votings[activeCancellation].finishTime > block.timestamp ) { locked += votingDecisions[activeCancellation][staker].amount; } return locked; } ///@dev get available tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals ///@param staker address of staker function getAvailableTokens(address staker) public view override returns (uint256 available) { uint256 locked = getLockedTokens(staker); uint256 staked = staking.getStakedTokens(staker); available = staked - locked; return available; } ///@dev returns all proposals from pool function getAllProposals() external view returns (Voting[] memory) { Voting[] memory proposalsList = new Voting[](10); // allocate array memory for (uint256 i = 0; i < proposals.length; i++) { { proposalsList[i] = votings[proposals[i]]; } } return proposalsList; } ///@dev returns all votings ///@return array of proposals from pool function getAllVotings() external view returns (Voting[] memory) { Voting[] memory votingsList = new Voting[](votingsCount); // allocate array memory for (uint256 i = 0; i < votingsCount; i++) { { votingsList[i] = votings[i + 1]; } } return votingsList; } ///@dev returns proposal info with additional information for frontend ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveVoting() external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens( votings[activeVoting].creator ); return ( votings[activeVoting], creatorAmountStaked, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveCancellation() external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens( votings[activeCancellation].creator ); return ( votings[activeCancellation], creatorAmountStaked, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveVoting(address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens( votings[activeVoting].creator ); return ( votings[activeVoting], votingDecisions[activeVoting][user], creatorAmountStaked, available, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveCancellation(address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens( votings[activeCancellation].creator ); return ( votings[activeCancellation], votingDecisions[activeCancellation][user], creatorAmountStaked, available, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param id id of proposal ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getProposalInfo(uint256 id) external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens(votings[id].creator); return ( votings[id], creatorAmountStaked, votings[id].status == Status.proposal ? proposalQuorum : votingQuorum, votings[id].status == Status.proposal ? proposalMajority : votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param id id of proposal ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getProposalInfo(uint256 id, address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens(votings[id].creator); return ( votings[id], votingDecisions[id][user], creatorAmountStaked, available, votings[id].status == Status.proposal ? proposalQuorum : votingQuorum, votings[id].status == Status.proposal ? proposalMajority : votingMajority ); } ///@dev returns DAO configuration parameters ///@return allocation config ///@return strategy config ///@return proposal majority ///@return main voting round majority ///@return proposal quorum ///@return main voting round quorum function InfoDAO() external view returns ( Allocation memory, Strategy memory, uint256, uint256, uint256, uint256 ) { return ( allocation, strategy, proposalMajority, votingMajority, proposalQuorum, votingQuorum ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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]{40}) is missing role (0x[0-9a-f]{64})$/ */ 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, 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()); } } } // 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.4; ///@title Interface for PLBTSTaking contract for DAO interactions interface IPLBTStaking { ///@dev returns amount of staked tokens by user `_address` ///@param _address address of the user ///@return amount of tokens function getStakedTokens(address _address) external view returns (uint256); ///@dev sets reward for next distribution time ///@param _amountWETH amount of wETH tokens ///@param _amountWBTC amount of wBTC tokens function setReward(uint256 _amountWETH, uint256 _amountWBTC) external; ///@dev changes treasury address ///@param _treasury address of the treasury function changeTreasury(address _treasury) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; interface IDAO { function getLockedTokens(address staker) external view returns(uint256 locked); function getAvailableTokens(address staker) external view returns(uint256 locked); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } /* ERC20FriendlyRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./interfaces/IRewardModule.sol"; import "./interfaces/IEvents.sol"; import "./ERC20BaseRewardModule.sol"; import "./GysrUtils.sol"; /** * @title ERC20 friendly reward module * * @notice this reward module distributes a single ERC20 token as the staking reward. * It is designed to offer simple and predictable reward mechanics. * * @dev rewards are immutable once earned, and can be claimed by the user at * any time. The module can be configured with a linear vesting schedule to * incentivize longer term staking. The user can spend GYSR at the time of * staking to receive a multiplier on their earning rate. */ contract ERC20FriendlyRewardModule is ERC20BaseRewardModule { using GysrUtils for uint256; // constants uint256 public constant FULL_VESTING = 10**DECIMALS; // single stake by user struct Stake { uint256 shares; uint256 gysr; uint256 bonus; uint256 rewardTally; uint256 timestamp; } // mapping of user to all of their stakes mapping(address => Stake[]) public stakes; // total shares without GYSR multiplier applied uint256 public totalRawStakingShares; // total shares with GYSR multiplier applied uint256 public totalStakingShares; // counter representing the current rate of rewards per share uint256 public rewardsPerStakedShare; // value to keep track of earnings to be put back into the pool uint256 public rewardDust; // timestamp of last update uint256 public lastUpdated; // minimum ratio of earned rewards measured against FULL_VESTING (i.e. 2.5 * 10^17 would be 25%) uint256 public immutable vestingStart; // length of time in seconds until the user receives a FULL_VESTING (1x) multiplier on rewards uint256 public immutable vestingPeriod; IERC20 private immutable _token; address private immutable _factory; /** * @param token_ the token that will be rewarded * @param vestingStart_ minimum ratio earned * @param vestingPeriod_ period (in seconds) over which investors vest to 100% * @param factory_ address of module factory */ constructor( address token_, uint256 vestingStart_, uint256 vestingPeriod_, address factory_ ) { require(vestingStart_ <= FULL_VESTING, "frm1"); _token = IERC20(token_); _factory = factory_; vestingStart = vestingStart_; vestingPeriod = vestingPeriod_; lastUpdated = block.timestamp; } /** * @inheritdoc IRewardModule */ function tokens() external view override returns (address[] memory tokens_) { tokens_ = new address[](1); tokens_[0] = address(_token); } /** * @inheritdoc IRewardModule */ function factory() external view override returns (address) { return _factory; } /** * @inheritdoc IRewardModule */ function balances() external view override returns (uint256[] memory balances_) { balances_ = new uint256[](1); balances_[0] = totalLocked(); } /** * @inheritdoc IRewardModule */ function usage() external view override returns (uint256) { return _usage(); } /** * @inheritdoc IRewardModule */ function stake( address account, address user, uint256 shares, bytes calldata data ) external override onlyOwner returns (uint256, uint256) { _update(); return _stake(account, user, shares, data); } /** * @notice internal implementation of stake method * @param account address of staking account * @param user address of user * @param shares number of new shares minted * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function _stake( address account, address user, uint256 shares, bytes calldata data ) internal returns (uint256, uint256) { require(data.length == 0 || data.length == 32, "frm2"); uint256 gysr; if (data.length == 32) { assembly { gysr := calldataload(164) } } uint256 bonus = gysr.gysrBonus(shares, totalRawStakingShares + shares, _usage()); if (gysr > 0) { emit GysrSpent(user, gysr); } // update user staking info stakes[account].push( Stake(shares, gysr, bonus, rewardsPerStakedShare, block.timestamp) ); // add new shares to global totals totalRawStakingShares += shares; totalStakingShares += (shares * bonus) / 10**DECIMALS; return (gysr, 0); } /** * @inheritdoc IRewardModule */ function unstake( address account, address user, uint256 shares, bytes calldata ) external override onlyOwner returns (uint256, uint256) { _update(); return _unstake(account, user, shares); } /** * @notice internal implementation of unstake * @param account address of staking account * @param user address of user * @param shares number of shares burned * @return amount of gysr spent * @return amount of gysr vested */ function _unstake( address account, address user, uint256 shares ) internal returns (uint256, uint256) { // redeem first-in-last-out uint256 sharesLeftToBurn = shares; Stake[] storage userStakes = stakes[account]; uint256 rewardAmount; uint256 gysrVested; uint256 preVestingRewards; uint256 timeVestingCoeff; while (sharesLeftToBurn > 0) { Stake storage lastStake = userStakes[userStakes.length - 1]; if (lastStake.shares <= sharesLeftToBurn) { // fully redeem a past stake preVestingRewards = _rewardForStakedShares( lastStake.shares, lastStake.bonus, lastStake.rewardTally ); timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp); rewardAmount += (preVestingRewards * timeVestingCoeff) / 10**DECIMALS; rewardDust += (preVestingRewards * (FULL_VESTING - timeVestingCoeff)) / 10**DECIMALS; totalStakingShares -= (lastStake.shares * lastStake.bonus) / 10**DECIMALS; sharesLeftToBurn -= lastStake.shares; gysrVested += lastStake.gysr; userStakes.pop(); } else { // partially redeem a past stake preVestingRewards = _rewardForStakedShares( sharesLeftToBurn, lastStake.bonus, lastStake.rewardTally ); timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp); rewardAmount += (preVestingRewards * timeVestingCoeff) / 10**DECIMALS; rewardDust += (preVestingRewards * (FULL_VESTING - timeVestingCoeff)) / 10**DECIMALS; totalStakingShares -= (sharesLeftToBurn * lastStake.bonus) / 10**DECIMALS; uint256 partialVested = (sharesLeftToBurn * lastStake.gysr) / lastStake.shares; gysrVested += partialVested; lastStake.shares -= sharesLeftToBurn; lastStake.gysr -= partialVested; sharesLeftToBurn = 0; } } // update global totals totalRawStakingShares -= shares; if (rewardAmount > 0) { _distribute(user, address(_token), rewardAmount); } if (gysrVested > 0) { emit GysrVested(user, gysrVested); } return (0, gysrVested); } /** * @inheritdoc IRewardModule */ function claim( address account, address user, uint256 shares, bytes calldata data ) external override onlyOwner returns (uint256 spent, uint256 vested) { _update(); (, vested) = _unstake(account, user, shares); (spent, ) = _stake(account, user, shares, data); } /** * @dev compute rewards owed for a specific stake * @param shares number of shares to calculate rewards for * @param bonus associated bonus for this stake * @param rewardTally associated rewardTally for this stake * @return reward for these staked shares */ function _rewardForStakedShares( uint256 shares, uint256 bonus, uint256 rewardTally ) internal view returns (uint256) { return ((((rewardsPerStakedShare - rewardTally) * shares) / 10**DECIMALS) * // counteract rewardsPerStakedShare coefficient bonus) / 10**DECIMALS; // counteract bonus coefficient } /** * @notice compute vesting multiplier as function of staking time * @param time epoch time at which the tokens were staked * @return vesting multiplier rewards */ function timeVestingCoefficient(uint256 time) public view returns (uint256) { if (vestingPeriod == 0) return FULL_VESTING; uint256 stakeTime = block.timestamp - time; if (stakeTime > vestingPeriod) return FULL_VESTING; return vestingStart + (stakeTime * (FULL_VESTING - vestingStart)) / vestingPeriod; } /** * @inheritdoc IRewardModule */ function update(address) external override { requireOwner(); _update(); } /** * @notice method called ad hoc to clean up and perform additional accounting * @dev will only be called manually, and should not contain any essential logic */ function clean() external override { requireOwner(); _update(); _clean(address(_token)); } /** * @notice fund Geyser by locking up reward tokens for distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked */ function fund(uint256 amount, uint256 duration) external { _update(); _fund(address(_token), amount, duration, block.timestamp); } /** * @notice fund Geyser by locking up reward tokens for distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked * @param start time (seconds) at which funding begins to unlock */ function fund( uint256 amount, uint256 duration, uint256 start ) external { _update(); _fund(address(_token), amount, duration, start); } /** * @dev updates the internal accounting for rewards per staked share * retrieves unlocked tokens and adds on any unvested rewards from the last unstake operation */ function _update() private { lastUpdated = block.timestamp; if (totalStakingShares == 0) { rewardsPerStakedShare = 0; return; } uint256 rewardsToUnlock = _unlockTokens(address(_token)) + rewardDust; rewardDust = 0; // global accounting rewardsPerStakedShare += (rewardsToUnlock * 10**DECIMALS) / totalStakingShares; } /** * @return total number of locked reward tokens */ function totalLocked() public view returns (uint256) { if (lockedShares(address(_token)) == 0) { return 0; } return (_token.balanceOf(address(this)) * lockedShares(address(_token))) / totalShares(address(_token)); } /** * @return total number of unlocked reward tokens */ function totalUnlocked() public view returns (uint256) { uint256 unlockedShares = totalShares(address(_token)) - lockedShares(address(_token)); if (unlockedShares == 0) { return 0; } return (_token.balanceOf(address(this)) * unlockedShares) / totalShares(address(_token)); } /** * @dev internal helper to get current usage ratio * @return GYSR usage ratio */ function _usage() private view returns (uint256) { if (totalStakingShares == 0) { return 0; } return ((totalStakingShares - totalRawStakingShares) * 10**DECIMALS) / totalStakingShares; } /** * @param addr address of interest * @return number of active stakes for user */ function stakeCount(address addr) public view returns (uint256) { return stakes[addr].length; } } /* PoolFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IModuleFactory.sol"; import "./interfaces/IStakingModule.sol"; import "./interfaces/IRewardModule.sol"; import "./OwnerController.sol"; import "./Pool.sol"; /** * @title Pool factory * * @notice this implements the Pool factory contract which allows any user to * easily configure and deploy their own Pool * * @dev it relies on a system of sub-factories which are responsible for the * creation of underlying staking and reward modules. This primary factory * calls each module factory and assembles the overall Pool contract. * * this contract also manages various privileged platform settings including * treasury address, fee amount, and module factory whitelist. */ contract PoolFactory is IPoolFactory, OwnerController { // events event PoolCreated(address indexed user, address pool); event FeeUpdated(uint256 previous, uint256 updated); event TreasuryUpdated(address previous, address updated); event WhitelistUpdated( address indexed factory, uint256 previous, uint256 updated ); // types enum ModuleFactoryType {Unknown, Staking, Reward} // constants uint256 public constant MAX_FEE = 20 * 10**16; // 20% // fields mapping(address => bool) public map; address[] public list; address private _gysr; address private _treasury; uint256 private _fee; mapping(address => ModuleFactoryType) public whitelist; /** * @param gysr_ address of GYSR token */ constructor(address gysr_, address treasury_) { _gysr = gysr_; _treasury = treasury_; _fee = MAX_FEE; } /** * @notice create a new Pool * @param staking address of factory that will be used to create staking module * @param reward address of factory that will be used to create reward module * @param stakingdata construction data for staking module factory * @param rewarddata construction data for reward module factory * @return address of newly created Pool */ function create( address staking, address reward, bytes calldata stakingdata, bytes calldata rewarddata ) external returns (address) { // validate require(whitelist[staking] == ModuleFactoryType.Staking, "f1"); require(whitelist[reward] == ModuleFactoryType.Reward, "f2"); // create modules address stakingModule = IModuleFactory(staking).createModule(stakingdata); address rewardModule = IModuleFactory(reward).createModule(rewarddata); // create pool Pool pool = new Pool(stakingModule, rewardModule, _gysr, address(this)); // set access IStakingModule(stakingModule).transferOwnership(address(pool)); IRewardModule(rewardModule).transferOwnership(address(pool)); pool.transferControl(msg.sender); // this also sets controller for modules pool.transferOwnership(msg.sender); // bookkeeping map[address(pool)] = true; list.push(address(pool)); // output emit PoolCreated(msg.sender, address(pool)); return address(pool); } /** * @inheritdoc IPoolFactory */ function treasury() external view override returns (address) { return _treasury; } /** * @inheritdoc IPoolFactory */ function fee() external view override returns (uint256) { return _fee; } /** * @notice update the GYSR treasury address * @param treasury_ new value for treasury address */ function setTreasury(address treasury_) external { requireController(); emit TreasuryUpdated(_treasury, treasury_); _treasury = treasury_; } /** * @notice update the global GYSR spending fee * @param fee_ new value for GYSR spending fee */ function setFee(uint256 fee_) external { requireController(); require(fee_ <= MAX_FEE, "f3"); emit FeeUpdated(_fee, fee_); _fee = fee_; } /** * @notice set the whitelist status of a module factory * @param factory_ address of module factory * @param type_ updated whitelist status for module */ function setWhitelist(address factory_, uint256 type_) external { requireController(); require(type_ <= uint256(ModuleFactoryType.Reward), "f4"); require(factory_ != address(0), "f5"); emit WhitelistUpdated(factory_, uint256(whitelist[factory_]), type_); whitelist[factory_] = ModuleFactoryType(type_); } /** * @return total number of Pools created by the factory */ function count() public view returns (uint256) { return list.length; } } /* IPool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool interface * * @notice this defines the core Pool contract interface */ interface IPool { /** * @return staking tokens for Pool */ function stakingTokens() external view returns (address[] memory); /** * @return reward tokens for Pool */ function rewardTokens() external view returns (address[] memory); /** * @return staking balances for user */ function stakingBalances(address user) external view returns (uint256[] memory); /** * @return total staking balances for Pool */ function stakingTotals() external view returns (uint256[] memory); /** * @return reward balances for Pool */ function rewardBalances() external view returns (uint256[] memory); /** * @return GYSR usage ratio for Pool */ function usage() external view returns (uint256); /** * @return address of staking module */ function stakingModule() external view returns (address); /** * @return address of reward module */ function rewardModule() external view returns (address); /** * @notice stake asset and begin earning rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice unstake asset and claim rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice claim rewards without unstaking * @param amount number of tokens to claim against * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice method called ad hoc to update user accounting */ function update() external; /** * @notice method called ad hoc to clean up and perform additional accounting */ function clean() external; /** * @return gysr balance available for withdrawal */ function gysrBalance() external view returns (uint256); /** * @notice withdraw GYSR tokens applied during unstaking * @param amount number of GYSR to withdraw */ function withdraw(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: 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: GPL-3.0 pragma solidity >=0.6.2; 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); } /* IRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Reward module interface * * @notice this contract defines the common interface that any reward module * must implement to be compatible with the modular Pool architecture. */ abstract contract IRewardModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of reward tokens */ function tokens() external view virtual returns (address[] memory); /** * @return array of reward token balances */ function balances() external view virtual returns (uint256[] memory); /** * @return GYSR usage ratio for reward module */ function usage() external view virtual returns (uint256); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice perform any necessary accounting for new stake * @param account address of staking account * @param user address of user * @param shares number of new shares minted * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function stake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform any necessary accounting for unstake * @param account address of staking account * @param user address of user * @param shares number of shares burned * @param data additional data * @return amount of gysr spent * @return amount of gysr vested */ function unstake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform and necessary accounting for existing stake * @param account address of staking account * @param user address of user * @param shares number of shares being claimed against * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function claim( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } /* IEvents https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title GYSR event system * * @notice common interface to define GYSR event system */ interface IEvents { // staking event Staked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Unstaked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Claimed( address indexed user, address indexed token, uint256 amount, uint256 shares ); // rewards event RewardsDistributed( address indexed user, address indexed token, uint256 amount, uint256 shares ); event RewardsFunded( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); event RewardsUnlocked(address indexed token, uint256 shares); event RewardsExpired( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); // gysr event GysrSpent(address indexed user, uint256 amount); event GysrVested(address indexed user, uint256 amount); event GysrWithdrawn(uint256 amount); } /* ERC20BaseRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IRewardModule.sol"; /** * @title ERC20 base reward module * * @notice this abstract class implements common ERC20 funding and unlocking * logic, which is inherited by other reward modules. */ abstract contract ERC20BaseRewardModule is IRewardModule { using SafeERC20 for IERC20; // single funding/reward schedule struct Funding { uint256 amount; uint256 shares; uint256 locked; uint256 updated; uint256 start; uint256 duration; } // constants uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6; uint256 public constant MAX_ACTIVE_FUNDINGS = 16; // funding/reward state fields mapping(address => Funding[]) private _fundings; mapping(address => uint256) private _shares; mapping(address => uint256) private _locked; /** * @notice getter for total token shares */ function totalShares(address token) public view returns (uint256) { return _shares[token]; } /** * @notice getter for total locked token shares */ function lockedShares(address token) public view returns (uint256) { return _locked[token]; } /** * @notice getter for funding schedule struct */ function fundings(address token, uint256 index) public view returns ( uint256 amount, uint256 shares, uint256 locked, uint256 updated, uint256 start, uint256 duration ) { Funding storage f = _fundings[token][index]; return (f.amount, f.shares, f.locked, f.updated, f.start, f.duration); } /** * @param token contract address of reward token * @return number of active funding schedules */ function fundingCount(address token) public view returns (uint256) { return _fundings[token].length; } /** * @notice compute number of unlockable shares for a specific funding schedule * @param token contract address of reward token * @param idx index of the funding * @return the number of unlockable shares */ function unlockable(address token, uint256 idx) public view returns (uint256) { Funding storage funding = _fundings[token][idx]; // funding schedule is in future if (block.timestamp < funding.start) { return 0; } // empty if (funding.locked == 0) { return 0; } // handle zero-duration period or leftover dust from integer division if (block.timestamp >= funding.start + funding.duration) { return funding.locked; } return ((block.timestamp - funding.updated) * funding.shares) / funding.duration; } /** * @notice fund pool by locking up reward tokens for future distribution * @param token contract address of reward token * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked * @param start time (seconds) at which funding begins to unlock */ function _fund( address token, uint256 amount, uint256 duration, uint256 start ) internal { requireController(); // validate require(amount > 0, "rm1"); require(start >= block.timestamp, "rm2"); require(_fundings[token].length < MAX_ACTIVE_FUNDINGS, "rm3"); IERC20 rewardToken = IERC20(token); // do transfer of funding uint256 total = rewardToken.balanceOf(address(this)); rewardToken.safeTransferFrom(msg.sender, address(this), amount); uint256 actual = rewardToken.balanceOf(address(this)) - total; // mint shares at current rate uint256 minted = (total > 0) ? (_shares[token] * actual) / total : actual * INITIAL_SHARES_PER_TOKEN; _locked[token] += minted; _shares[token] += minted; // create new funding _fundings[token].push( Funding({ amount: amount, shares: minted, locked: minted, updated: start, start: start, duration: duration }) ); emit RewardsFunded(token, amount, minted, start); } /** * @dev internal function to clean up stale funding schedules * @param token contract address of reward token to clean up */ function _clean(address token) internal { // check for stale funding schedules to expire uint256 removed = 0; uint256 originalSize = _fundings[token].length; for (uint256 i = 0; i < originalSize; i++) { Funding storage funding = _fundings[token][i - removed]; uint256 idx = i - removed; if ( unlockable(token, idx) == 0 && block.timestamp >= funding.start + funding.duration ) { emit RewardsExpired( token, funding.amount, funding.shares, funding.start ); // remove at idx by copying last element here, then popping off last // (we don't care about order) _fundings[token][idx] = _fundings[token][ _fundings[token].length - 1 ]; _fundings[token].pop(); removed++; } } } /** * @dev unlocks reward tokens based on funding schedules * @param token contract addres of reward token * @return shares number of shares unlocked */ function _unlockTokens(address token) internal returns (uint256 shares) { // get unlockable shares for each funding schedule for (uint256 i = 0; i < _fundings[token].length; i++) { uint256 s = unlockable(token, i); Funding storage funding = _fundings[token][i]; if (s > 0) { funding.locked -= s; funding.updated = block.timestamp; shares += s; } } // do unlocking if (shares > 0) { _locked[token] -= shares; emit RewardsUnlocked(token, shares); } } /** * @dev distribute reward tokens to user * @param user address of user receiving rweard * @param token contract address of reward token * @param shares number of shares to be distributed * @return amount number of reward tokens distributed */ function _distribute( address user, address token, uint256 shares ) internal returns (uint256 amount) { // compute reward amount in tokens IERC20 rewardToken = IERC20(token); amount = (rewardToken.balanceOf(address(this)) * shares) / _shares[token]; // update overall reward shares _shares[token] -= shares; // do reward rewardToken.safeTransfer(user, amount); emit RewardsDistributed(user, token, amount, shares); } } /* GYSRUtils https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./MathUtils.sol"; /** * @title GYSR utilities * * @notice this library implements utility methods for the GYSR multiplier * and spending mechanics */ library GysrUtils { using MathUtils for int128; // constants uint256 public constant DECIMALS = 18; uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1% /** * @notice compute GYSR bonus as a function of usage ratio, stake amount, * and GYSR spent * @param gysr number of GYSR token applied to bonus * @param amount number of tokens or shares to unstake * @param total number of tokens or shares in overall pool * @param ratio usage ratio from 0 to 1 * @return multiplier value */ function gysrBonus( uint256 gysr, uint256 amount, uint256 total, uint256 ratio ) internal pure returns (uint256) { if (amount == 0) { return 0; } if (total == 0) { return 0; } if (gysr == 0) { return 10**DECIMALS; } // scale GYSR amount with respect to proportion uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS; if (amount > portion) { gysr = (gysr * portion) / amount; } // 1 + gysr / (0.01 + ratio) uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio); return 10**DECIMALS + (uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) / 2**64; } } /* OwnerController https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Owner controller * * @notice this base contract implements an owner-controller access model. * * @dev the contract is an adapted version of the OpenZeppelin Ownable contract. * It allows the owner to designate an additional account as the controller to * perform restricted operations. * * Other changes include supporting role verification with a require method * in addition to the modifier option, and removing some unneeded functionality. * * Original contract here: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ contract OwnerController { address private _owner; address private _controller; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event ControlTransferred( address indexed previousController, address indexed newController ); constructor() { _owner = msg.sender; _controller = msg.sender; emit OwnershipTransferred(address(0), _owner); emit ControlTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current controller. */ function controller() public view returns (address) { return _controller; } /** * @dev Modifier that throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "oc1"); _; } /** * @dev Modifier that throws if called by any account other than the controller. */ modifier onlyController() { require(_controller == msg.sender, "oc2"); _; } /** * @dev Throws if called by any account other than the owner. */ function requireOwner() internal view { require(_owner == msg.sender, "oc1"); } /** * @dev Throws if called by any account other than the controller. */ function requireController() internal view { require(_controller == msg.sender, "oc2"); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). This can * include renouncing ownership by transferring to the zero address. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual { requireOwner(); require(newOwner != address(0), "oc3"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers control of the contract to a new account (`newController`). * Can only be called by the owner. */ function transferControl(address newController) public virtual { requireOwner(); require(newController != address(0), "oc4"); emit ControlTransferred(_controller, newController); _controller = newController; } } // 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); } } } } /* MathUtils https://github.com/gysr-io/core SPDX-License-Identifier: BSD-4-Clause */ pragma solidity 0.8.4; /** * @title Math utilities * * @notice this library implements various logarithmic math utilies which support * other contracts and specifically the GYSR multiplier calculation * * @dev h/t https://github.com/abdk-consulting/abdk-libraries-solidity */ library MathUtils { /** * @notice calculate binary logarithm of x * * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function logbase2(int128 x) internal pure returns (int128) { unchecked { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(int256(x)) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } } /** * @notice calculate natural logarithm of x * @dev magic constant comes from ln(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { unchecked { require(x > 0); return int128( int256( (uint256(int256(logbase2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ) ); } } /** * @notice calculate logarithm base 10 of x * @dev magic constant comes from log10(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function logbase10(int128 x) internal pure returns (int128) { require(x > 0); return int128( int256( (uint256(int256(logbase2(x))) * 0x4d104d427de7fce20a6e420e02236748) >> 128 ) ); } // wrapper functions to allow testing function testlogbase2(int128 x) public pure returns (int128) { return logbase2(x); } function testlogbase10(int128 x) public pure returns (int128) { return logbase10(x); } } /* IPoolFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool factory interface * * @notice this defines the Pool factory interface, primarily intended for * the Pool contract to interact with */ interface IPoolFactory { /** * @return GYSR treasury address */ function treasury() external view returns (address); /** * @return GYSR spending fee */ function fee() external view returns (uint256); } /* IModuleFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Module factory interface * * @notice this defines the common module factory interface used by the * main factory to create the staking and reward modules for a new Pool. */ interface IModuleFactory { // events event ModuleCreated(address indexed user, address module); /** * @notice create a new Pool module * @param data binary encoded construction parameters * @return address of newly created module */ function createModule(bytes calldata data) external returns (address); } /* IStakingModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Staking module interface * * @notice this contract defines the common interface that any staking module * must implement to be compatible with the modular Pool architecture. */ abstract contract IStakingModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of staking tokens */ function tokens() external view virtual returns (address[] memory); /** * @notice get balance of user * @param user address of user * @return balances of each staking token */ function balances(address user) external view virtual returns (uint256[] memory); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice get total staked amount * @return totals for each staking token */ function totals() external view virtual returns (uint256[] memory); /** * @notice stake an amount of tokens for user * @param user address of user * @param amount number of tokens to stake * @param data additional data * @return address of staking account * @return number of shares minted for stake */ function stake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice unstake an amount of tokens for user * @param user address of user * @param amount number of tokens to unstake * @param data additional data * @return address of staking account * @return number of shares burned for unstake */ function unstake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice quote the share value for an amount of tokens without unstaking * @param user address of user * @param amount number of tokens to claim with * @param data additional data * @return address of staking account * @return number of shares that the claim amount is worth */ function claim( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } /* Pool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IPool.sol"; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IStakingModule.sol"; import "./interfaces/IRewardModule.sol"; import "./interfaces/IEvents.sol"; import "./OwnerController.sol"; /** * @title Pool * * @notice this implements the GYSR core Pool contract. It supports generalized * incentive mechanisms through a modular architecture, where * staking and reward logic is contained in child contracts. */ contract Pool is IPool, IEvents, ReentrancyGuard, OwnerController { using SafeERC20 for IERC20; // constants uint256 public constant DECIMALS = 18; // modules IStakingModule private immutable _staking; IRewardModule private immutable _reward; // gysr fields IERC20 private immutable _gysr; IPoolFactory private immutable _factory; uint256 private _gysrVested; /** * @param staking_ the staking module address * @param reward_ the reward module address * @param gysr_ address for GYSR token * @param factory_ address for parent factory */ constructor( address staking_, address reward_, address gysr_, address factory_ ) { _staking = IStakingModule(staking_); _reward = IRewardModule(reward_); _gysr = IERC20(gysr_); _factory = IPoolFactory(factory_); } // -- IPool -------------------------------------------------------------- /** * @inheritdoc IPool */ function stakingTokens() external view override returns (address[] memory) { return _staking.tokens(); } /** * @inheritdoc IPool */ function rewardTokens() external view override returns (address[] memory) { return _reward.tokens(); } /** * @inheritdoc IPool */ function stakingBalances(address user) external view override returns (uint256[] memory) { return _staking.balances(user); } /** * @inheritdoc IPool */ function stakingTotals() external view override returns (uint256[] memory) { return _staking.totals(); } /** * @inheritdoc IPool */ function rewardBalances() external view override returns (uint256[] memory) { return _reward.balances(); } /** * @inheritdoc IPool */ function usage() external view override returns (uint256) { return _reward.usage(); } /** * @inheritdoc IPool */ function stakingModule() external view override returns (address) { return address(_staking); } /** * @inheritdoc IPool */ function rewardModule() external view override returns (address) { return address(_reward); } /** * @inheritdoc IPool */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.stake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.stake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.unstake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.unstake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.claim(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.claim(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function update() external override nonReentrant { _staking.update(msg.sender); _reward.update(msg.sender); } /** * @inheritdoc IPool */ function clean() external override nonReentrant { requireController(); _staking.clean(); _reward.clean(); } /** * @inheritdoc IPool */ function gysrBalance() external view override returns (uint256) { return _gysrVested; } /** * @inheritdoc IPool */ function withdraw(uint256 amount) external override { requireController(); require(amount > 0, "p1"); require(amount <= _gysrVested, "p2"); // do transfer _gysr.safeTransfer(msg.sender, amount); _gysrVested = _gysrVested - amount; emit GysrWithdrawn(amount); } /** * @notice transfer control of the Pool and modules to another account * @param newController address of new controller */ function transferControl(address newController) public override { super.transferControl(newController); _staking.transferControl(newController); _reward.transferControl(newController); } // -- Pool internal ----------------------------------------------------- /** * @dev private method to process GYSR spending and vesting * @param spent number of tokens to unstake * @param vested data passed to staking module */ function _processGysr(uint256 spent, uint256 vested) private { // spending if (spent > 0) { _gysr.safeTransferFrom(msg.sender, address(this), spent); } // vesting if (vested > 0) { uint256 fee = (vested * _factory.fee()) / 10**DECIMALS; if (fee > 0) { _gysr.safeTransfer(_factory.treasury(), fee); } _gysrVested = _gysrVested + vested - fee; } } } // SPDX-License-Identifier: MIT 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; } }
@dev modifier used for restricted function execution
modifier onlyDAO() { require( msg.sender == address(this), "DAO: only dao can call this function." ); _; } IERC20 private weth; IERC20 private wbtc; this.changeStrategy.selector, this.changeAllocation.selector, this.changeQuorum.selector, this.changeMajority.selector, this.changeTreasury.selector, this.cancelVoting.selector ]; mapping(uint256 => Voting) public votings; uint256 _proposalMajority, uint256 _votingMajority, uint256 _proposalQuorum, uint256 _votingQuorum, uint256 _votingPeriod, uint256 _regularTimelock, uint256 _cancelTimelock, Allocation memory _allocation, Strategy memory _strategy
558,296
[ 1, 20597, 1399, 364, 15693, 445, 4588, 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, 9606, 1338, 18485, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 1758, 12, 2211, 3631, 203, 5411, 315, 18485, 30, 1338, 15229, 848, 745, 333, 445, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 467, 654, 39, 3462, 3238, 341, 546, 31, 203, 565, 467, 654, 39, 3462, 3238, 17298, 5111, 31, 203, 203, 3639, 333, 18, 3427, 4525, 18, 9663, 16, 203, 3639, 333, 18, 3427, 17353, 18, 9663, 16, 203, 3639, 333, 18, 3427, 31488, 18, 9663, 16, 203, 3639, 333, 18, 3427, 17581, 560, 18, 9663, 16, 203, 3639, 333, 18, 3427, 56, 266, 345, 22498, 18, 9663, 16, 203, 3639, 333, 18, 10996, 58, 17128, 18, 9663, 203, 565, 308, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 776, 17128, 13, 1071, 331, 352, 899, 31, 203, 203, 3639, 2254, 5034, 389, 685, 8016, 17581, 560, 16, 203, 3639, 2254, 5034, 389, 90, 17128, 17581, 560, 16, 203, 3639, 2254, 5034, 389, 685, 8016, 31488, 16, 203, 3639, 2254, 5034, 389, 90, 17128, 31488, 16, 203, 3639, 2254, 5034, 389, 90, 17128, 5027, 16, 203, 3639, 2254, 5034, 389, 16819, 10178, 292, 975, 16, 203, 3639, 2254, 5034, 389, 10996, 10178, 292, 975, 16, 203, 3639, 24242, 3778, 389, 29299, 16, 203, 3639, 19736, 3778, 389, 14914, 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 ]
pragma solidity 0.4.25; /* __ __ ___ ______ /\ \ __/\ \ /\_ \ /\__ _\ \ \ \/\ \ \ \ __\//\ \ ___ ___ ___ ___ __ \/_/\ \/ ___ \ \ \ \ \ \ \ /'__`\\ \ \ /'___\ / __`\ /' __` __`\ /'__`\ \ \ \ / __`\ \ \ \_/ \_\ \/\ __/ \_\ \_/\ \__//\ \L\ \/\ \/\ \/\ \/\ __/ \ \ \/\ \L\ \__ __ __ \ `\___x___/\ \____\/\____\ \____\ \____/\ \_\ \_\ \_\ \____\ \ \_\ \____/\_\/\_\/\_\ '\/__//__/ \/____/\/____/\/____/\/___/ \/_/\/_/\/_/\/____/ \/_/\/___/\/_/\/_/\/_/ __/\\\\\\\\\\\\\\\__/\\\_________________/\\\\\\\\\\\_______/\\\\\\\\\____ _\/\\\///////////__\/\\\_______________/\\\/////////\\\___/\\\\\\\\\\\\\__ _\/\\\_____________\/\\\______________\//\\\______\///___/\\\/////////\\\_ _\/\\\\\\\\\\\_____\/\\\_______________\////\\\_________\/\\\_______\/\\\_ _\/\\\///////______\/\\\__________________\////\\\______\/\\\\\\\\\\\\\\\_ _\/\\\_____________\/\\\_____________________\////\\\___\/\\\/////////\\\_ _\/\\\_____________\/\\\______________/\\\______\//\\\__\/\\\_______\/\\\_ _\/\\\\\\\\\\\\\\\_\/\\\\\\\\\\\\\\\_\///\\\\\\\\\\\/___\/\\\_______\/\\\_ _\///////////////__\///////////////____\///////////_____\///________\///__ // ---------------------------------------------------------------------------- // 'Elisia' contract with following features // => In-built ICO functionality // => ERC20 Compliance // => Higher control of ICO by owner // => selfdestruct functionality // => SafeMath implementation // => Air-drop // => User whitelisting // => Minting new tokens by owner // // Deployed to : 0x94eE9BdC075ff971207D888a9151970169279C82 // Symbol : ELSA // Name : Elisia // Total supply: 1,000,000,000 (1 Billion) // Reserved coins for ICO: 750,000,000 ELSA (750 Million) // Decimals : 18 // // Copyright (c) 2018 Elisia Inc. (https://Elisia.io) // Contract designed by EtherAuthority (https://EtherAuthority.io) // ---------------------------------------------------------------------------- */ //*******************************************************************// //------------------------ SafeMath Library -------------------------// //*******************************************************************// /** * @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; } } //*******************************************************************// //------------------ Contract to Manage Ownership -------------------// //*******************************************************************// contract owned { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } //***************************************************************// //------------------ ERC20 Standard Template -------------------// //***************************************************************// contract TokenERC20 { // Public variables of the token using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; uint256 public reservedForICO; bool public safeguard = false; //putting safeguard on will halt all non-owner functions // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply, uint256 allocatedForICO, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(1 ether); // Update total supply with the decimal amount reservedForICO = allocatedForICO.mul(1 ether); // Tokens reserved For ICO balanceOf[this] = reservedForICO; // 2.5 Billion ELC will remain in the contract balanceOf[msg.sender]=totalSupply.sub(reservedForICO); // Rest of tokens will be sent to owner name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(!safeguard); // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!safeguard); require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { require(!safeguard); allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { require(!safeguard); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(!safeguard); require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(!safeguard); require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } } //************************************************************************// //--------------------- ELISIA MAIN CODE STARTS HERE --------------------// //************************************************************************// contract Elisia is owned, TokenERC20 { /*************************************/ /* User whitelisting functionality */ /*************************************/ bool public whitelistingStatus = false; mapping (address => bool) public whitelisted; /** * Change whitelisting status on or off * * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. */ function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; } else{ whitelistingStatus = false; } } /** * Whitelist any user address - only Owner can do this * * It will add user address in whitelisted mapping */ function whitelistUser(address userAddress) onlyOwner public{ require(whitelistingStatus == true); require(userAddress != 0x0); whitelisted[userAddress] = true; } /** * Whitelist Many user address at once - only Owner can do this * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack * It will add user address in whitelisted mapping */ function whitelistManyUsers(address[] userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150); for(uint256 i = 0; i < addressCount; i++){ require(userAddresses[i] != 0x0); whitelisted[userAddresses[i]] = true; } } /*********************************/ /* Code for the ERC20 ELSA Token */ /*********************************/ /* Public variables of the token */ string private tokenName = "Elisia"; string private tokenSymbol = "ELSA"; uint256 private initialSupply = 1000000000; // 1 Billion uint256 private allocatedForICO = 750000000; // 750 Million /* Records for the fronzen accounts */ mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(!safeguard); require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /*******************************/ /* Code for the ELSA Crowdsale */ /*******************************/ /* TECHNICAL SPECIFICATIONS: => ICO starts : November 30th 6.00 GMT => ICO Ends : January 25th 23.59 GMT => Token Exchange Rate : 1 ETH = 10,000 ELSA (which equals to 1 ELSA = 0.0001 ETH) => Bonus Rounds: First 24 hours: 45% Day 2 - Day 7: 35% Day 8 - Day 14: 30% Day 15 - Day 21: 25% Day 22 - Day 28: 20% Day 29 - Day 35: 15% Day 36 - Day 42: 10% Day 43 - Day 49: 5% Day 50 - Day 56: NO BONUS => Coins reserved for ICO : 750,000,000 => Contribution Limits : No minimum or maximum Contribution */ //public variables for the Crowdsale uint256 public icoStartDate = 154355760 ; // 30 November 2018 06:00:00 - GMT uint256 public icoEndDate = 1548460740 ; // 25 January 2019 23:59:00 - GMT uint256 public exchangeRate = 10000; // 1 ETH = 10000 Tokens uint256 public tokensSold = 0; // how many tokens sold through crowdsale //@dev fallback function, only accepts ether if pre-sale or ICO is running or Reject function () payable external { require(!safeguard); require(!frozenAccount[msg.sender]); if(whitelistingStatus == true) { require(whitelisted[msg.sender]); } require(icoStartDate < now && icoEndDate > now); // calculate token amount to be sent uint256 token = msg.value.mul(exchangeRate); //weiamount * exchangeRate uint256 finalTokens = token.add(calculatePurchaseBonus(token)); //add bonus if available tokensSold = tokensSold.add(finalTokens); _transfer(this, msg.sender, finalTokens); //makes the transfers forwardEherToOwner(); //send Ether to owner } //calculating purchase bonus //SafeMath library is not used here at some places intentionally, as overflow is impossible here //And thus it saves gas cost if we avoid using SafeMath in such cases function calculatePurchaseBonus(uint256 token) internal view returns(uint256){ if(icoStartDate < now && (icoStartDate + 86400) > now ){ return token.mul(45).div(100); //45% bonus in first 24 hours } else if((icoStartDate + 86400) < now && (icoStartDate + (86400*7)) > now){ return token.mul(35).div(100); //Day 2 - Day 7: 35% } else if((icoStartDate + (86400*7)) < now && (icoStartDate + (86400*14)) > now){ return token.mul(30).div(100); //Day 8 - Day 14: 30% } else if((icoStartDate + (86400*14)) < now && (icoStartDate + (86400*21)) > now){ return token.mul(25).div(100); //Day 15 - Day 21: 25% } else if((icoStartDate + (86400*21)) < now && (icoStartDate + (86400*28)) > now){ return token.mul(20).div(100); //Day 22 - Day 28: 20% } else if((icoStartDate + (86400*28)) < now && (icoStartDate + (86400*35)) > now){ return token.mul(15).div(100); //Day 29 - Day 35: 15% } else if((icoStartDate + (86400*35)) < now && (icoStartDate + (86400*42)) > now){ return token.mul(10).div(100); //Day 36 - Day 42: 10% } else if((icoStartDate + (86400*42)) < now && (icoStartDate + (86400*49)) > now){ return token.mul(5).div(100); //Day 43 - Day 49: 5% } else{ return 0; // Day 50 - Day 56: NO BONUS } } //Automatocally forwards ether from smart contract to owner address function forwardEherToOwner() internal { address(owner).transfer(msg.value); } //Function to update an ICO parameter. //It requires: timestamp of start and end date, exchange rate (1 ETH = ? Tokens) //Owner need to make sure the contract has enough tokens for ICO. //If not enough, then he needs to transfer some tokens into contract addresss from his wallet //If there are no tokens in smart contract address, then ICO will not work. function updateCrowdsale(uint256 icoStartDateNew, uint256 icoEndDateNew, uint256 exchangeRateNew) onlyOwner public { require(icoStartDateNew < icoEndDateNew); icoStartDate = icoStartDateNew; icoEndDate = icoEndDateNew; exchangeRate = exchangeRateNew; } //Stops an ICO. //It will just set the ICO end date to zero and thus it will stop an ICO function stopICO() onlyOwner public{ icoEndDate = 0; } //function to check wheter ICO is running or not. //It will return current state of the crowdsale function icoStatus() public view returns(string){ if(icoStartDate < now && icoEndDate > now ){ return "ICO is running"; }else if(icoStartDate > now){ return "ICO will start on November 30th 6.00 GMT"; }else{ return "ICO is over"; } } //Function to set ICO Exchange rate. //1 ETH = How many Tokens ? function setICOExchangeRate(uint256 newExchangeRate) onlyOwner public { exchangeRate=newExchangeRate; } //Just in case, owner wants to transfer Tokens from contract to owner address function manualWithdrawToken(uint256 _amount) onlyOwner public { uint256 tokenAmount = _amount.mul(1 ether); _transfer(this, msg.sender, tokenAmount); } //Just in case, owner wants to transfer Ether from contract to owner address function manualWithdrawEther()onlyOwner public{ uint256 amount=address(this).balance; address(owner).transfer(amount); } //selfdestruct function. just in case owner decided to destruct this contract. function destructContract()onlyOwner public{ selfdestruct(owner); } /** * Change safeguard status on or off * * When safeguard is true, then all the non-owner functions will stop working. * When safeguard is false, then all the functions will resume working back again! */ function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } /*********************************/ /* Code for the Air drop of ELSA */ /*********************************/ /** * Run an Air-Drop * * It requires an array of all the addresses and amount of tokens to distribute * It will only process first 150 recipients. That limit is fixed to prevent gas limit */ function airdrop(address[] recipients,uint tokenAmount) public onlyOwner { uint256 addressCount = recipients.length; require(addressCount <= 150); for(uint i = 0; i < addressCount; i++) { //This will loop through all the recipients and send them the specified tokens _transfer(this, recipients[i], tokenAmount.mul(1 ether)); } } }
function to check wheter ICO is running or not.It will return current state of the crowdsale
function icoStatus() public view returns(string){ if(icoStartDate < now && icoEndDate > now ){ return "ICO is running"; return "ICO will start on November 30th 6.00 GMT"; return "ICO is over"; } }
14,114,888
[ 1, 915, 358, 866, 600, 847, 467, 3865, 353, 3549, 578, 486, 18, 7193, 903, 327, 783, 919, 434, 326, 276, 492, 2377, 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 ]
[ 1, 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, 3639, 445, 277, 2894, 1482, 1435, 1071, 1476, 1135, 12, 1080, 15329, 203, 5411, 309, 12, 10764, 22635, 411, 2037, 597, 277, 2894, 24640, 405, 2037, 262, 95, 203, 7734, 327, 315, 2871, 51, 353, 3549, 14432, 203, 7734, 327, 315, 2871, 51, 903, 787, 603, 423, 1527, 2558, 5196, 451, 1666, 18, 713, 21706, 14432, 203, 7734, 327, 315, 2871, 51, 353, 1879, 14432, 203, 5411, 289, 203, 3639, 289, 203, 540, 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 ]